package com.spice.im.chat;

import java.io.File;



















import java.io.IOException;


import java.net.URI;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.regex.Matcher;
import java.util.regex.Pattern;





























import android.annotation.SuppressLint;
import android.app.Activity;
//import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.res.AssetManager;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.Drawable;
import android.media.MediaPlayer;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.os.RemoteException;
import android.os.SystemClock;
import android.preference.PreferenceManager;
//import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.text.ClipboardManager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import baidumapsdk.demo.LocationDemo;
import net.tsz.afinal.FinalHttp;
//import net.tsz.afinal.bitmap.core.BitmapCache;
import net.tsz.afinal.http.AjaxCallBack;
import net.tsz.afinal.http.AjaxParams;

import org.jivesoftware.smack.packet.IQ;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smack.util.StringUtils;
import org.json.JSONException;
import org.json.JSONObject;

import cn.finalteam.galleryfinal.GalleryHelper;
import cn.finalteam.galleryfinal.GalleryImageLoader;
import cn.finalteam.galleryfinal.PhotoCropActivity;
import cn.finalteam.galleryfinal.PhotoTakeActivity;
//import cn.finalteam.galleryfinal.PhotoTakeActivity;
//import cn.finalteam.galleryfinal.MainActivity;
import cn.finalteam.galleryfinal.model.PhotoInfo;
import cn.finalteam.toolsfinal.BitmapUtils;
import cn.finalteam.toolsfinal.DateUtils;
import cn.finalteam.toolsfinal.DeviceUtils;
import cn.finalteam.toolsfinal.FileUtils;
import cn.finalteam.toolsfinal.Logger;

import com.dodola.model.DuitangInfoAdapter;
import com.dodola.model.UnReadMsgNumber;
import com.dodowaterfall.widget.FlowView;
import com.example.android.bitmapfun.util.Base64;
//import com.lidroid.xutils.bitmap.core.BitmapCache;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.speed.im.login.ContactGroupListIQ;
import com.speed.im.login.ContactGroupListIQResponse;
import com.speed.im.login.ContactGroupListIQResponseProvider;
import com.speed.im.login.EncryptionUtil;
//import com.spice.im.MainActivity;
import com.spice.im.ContactFrameActivity;
import com.spice.im.EmoteInputView;
import com.spice.im.EmoticonsEditText;
import com.spice.im.FlippingLoadingDialog;
import com.spice.im.MainListActivity;
import com.spice.im.OtherProfileActivity;
import com.spice.im.R;
//import com.spice.im.MainActivity.exPhoneCallListener;
import com.spice.im.chat.db.ChatMsgDao;
import com.spice.im.chat.file.FileActivity;
import com.spice.im.jspeex.voice.JSEncode;
import com.spice.im.jspeex.voice.JSpeexDec;
import com.spice.im.preference.PreferenceActivity.exPhoneCallListener;
import com.spice.im.ui.HandyTextView;
import com.spice.im.utils.AsyncTask;
import com.spice.im.utils.HeaderLayout;
import com.spice.im.utils.HeaderLayout.HeaderStyle;
import com.spice.im.utils.HeaderLayout.onRightImageButtonClickListener;
import com.stb.core.chat.ContactGroup;
import com.stb.isharemessage.BeemApplication;
import com.stb.isharemessage.IConnectionStatusCallback;
//import com.stb.isharemessage.service.Contact;
import com.stb.isharemessage.service.XmppConnectionAdapter;
import com.stb.isharemessage.service.aidl.IChat;
import com.stb.isharemessage.service.aidl.IChatManager;
import com.stb.isharemessage.service.aidl.IChatManagerListener;
import com.stb.isharemessage.service.aidl.IMessageListener;
import com.stb.isharemessage.service.aidl.IXmppFacade;
//import com.stb.isharemessage.ui.feed.EmoteInputView;
//import com.stb.isharemessage.ui.feed.EmoticonsEditText;
import com.stb.isharemessage.utils.BeemConnectivity;

import dalvik.system.VMRuntime;


/**
 * 聊天界面
 *
 * @author 白玉梁
 * @blog http://blog.csdn.net/baiyuliang2013
 * @weibo http://weibo.com/2611894214/profile?topnav=1&wvr=6&is_all=1
 */
//@SuppressLint("SimpleDateFormat")
public class ChatPullRefListActivity extends AppBaseActivity implements DropdownListView.OnRefreshListenerHeader,
        ChatAdapter.OnClickMsgListener,IConnectionStatusCallback {//, SpeechRecognizerUtil.RecoListener
	private static final String TAG = "ChatPullRefListActivity";
	private ChatAdapterOffline chatAdapterOffline;//20200317 增加纯粹为离线状态下的消息历史记录工具类
	private String AccountUser;
	private String Participant;
	private SharedPreferences sharedPrefs = null;
    private ViewPager mViewPager;
    private LinearLayout mDotsLayout;
    private EditText input;
    private TextView send;
    private DropdownListView mListView;
//    private ChatAdapter mLvAdapter;
    StaggeredAdapter mAdapter;
    private ChatMsgDao msgDao;

    private LinearLayout chat_face_container;
    
    private LinearLayout chat_add_container;
    private ImageView image_face;//表情图标
    private ImageView image_add;//更多图标
    private ImageView image_voice;//语音
    private TextView tv_weather,//图片
            tv_xingzuo,//拍照
            tv_joke,//笑话
            tv_loc,//位置
            tv_gg,//帅哥
            tv_mm,//美女
            tv_music;//歌曲
    
    private int REQUEST_VIDEO_CODE = 16;
    
//	protected EmoteInputView mInputView;
//	protected EmoticonsEditText mEetTextDitorEditer;
	
    
    private TextView voice_text;
    private ImageView image_keyboard;

    private LinearLayout ll_playing;//顶部正在播放布局
    private TextView tv_playing;

    //表情图标每页6列4行
    private int columns = 6;
    private int rows = 4;
    //每页显示的表情view
    private List<View> views = new ArrayList<View>();
    //表情列表
    private List<String> staticFacesList;
    //消息
    private List<Msg> listMsg;
    private SimpleDateFormat sd;
    private LayoutInflater inflater;
    private int offset;

    //发送者和接收者固定为小Q和自己
    private final String from = "xiaoq";//来自小Q
    private final String to = "master";//发送者为自己

    FinalHttp fh;
    AjaxParams ajaxParams;

    //在线音乐播放工具类
    MusicPlayManager musicPlayManager;
    // 语音听写工具
//    SpeechRecognizerUtil speechRecognizerUtil;
//    // 语音合成工具
//    SpeechSynthesizerUtil speechSynthesizerUtil;

    String voice_type;
    
    
	////////////20140210 start
	private String getRingRecordFileName() {
		Date date = new Date(System.currentTimeMillis());
		SimpleDateFormat dateFormat = new SimpleDateFormat("'speex'_yyyyMMdd_HHmmss");
		return dateFormat.format(date) + ".raw";//amr
	}
	private File file;
	private static final String PHOTOPATH2 = "beemphoto";
	private String RingRecordFilePath = "";
    final String start = Environment.getExternalStorageState();
    private static final String PHOTOPATH = "/beemphoto/"; 
    private String capturefilepath = "";
    private final static float TARGET_HEAP_UTILIZATION = 0.75f;
    private final static int CWJ_HEAP_SIZE = 6* 1024* 1024 ;
	//表情图标 biaoqing icon start 20130507
	private Dialog builder;
	private int[] imageIds = new int[107];
//	private TextView tvcontactname;
//	private String privatename="";
	private File fpath; 
//	private AudioRecorder mr;
//	private ARecorder mr;
    // 获取类的实例
    private ExtAudioRecorder recorder;
    //dialog显示的图片
    private Drawable[] micImages;
    
    
	private MediaPlayer mediaPlayer;
	private Thread recordThread;
	
	private static int MAX_TIME = 15;    //最长录制时间，单位秒，0为无时间限制
	private static int MIX_TIME = 1;     //最短录制时间，单位秒，0为无时间限制，建议设为1
	
	private static int RECORD_NO = 0;  //不在录音
	private static int RECORD_ING = 1;   //正在录音
	private static int RECODE_ED = 2;   //完成录音
	
	private static int RECODE_STATE = 0;      //录音的状态
	
	private static float recodeTime=0.0f;    //录音的时间
	private static double voiceValue=0.0;    //麦克风获取的音量值
	
	private ImageView dialog_img;
	private static boolean playState = false;  //播放状态
	private boolean isShosrt = false;
	private LinearLayout  voice_rcd_hint_loading,voice_rcd_hint_rcding,
			voice_rcd_hint_tooshort,voice_rcd_hint_toolong;//voice_rcd_hint_loading,
	private ImageView img1, sc_img1;
	private View rcChat_popup;
	private LinearLayout del_re;
	private ImageView volume;//录音动画图片
    public void setVolumeImage(Drawable drawable){
    	volume.setImageDrawable(drawable);
    }
	private boolean btn_vocie = false;
	private int flag = 1;
	private long startVoiceT, endVoiceT;
//	private Handler mVoiceHandler = new Handler();
//	private AnimationDrawable animationDrawable;  
//	private ImageView animationIV;
	////////////20140210 end

//    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                	mAdapter.notifyDataSetChanged();
                    break;
                case 2:
                    Music music = (Music) msg.obj;
                    if (music == null) {
                        changeList(Const.MSG_TYPE_TEXT, "歌曲获取失败");
                    } else {
                        changeList(Const.MSG_TYPE_MUSIC, music.getMusicUrl() + Const.SPILT + music.getTitle() + Const.SPILT + music.getDescription());
                    }
                    break;
                case 3:
                	loadingDialog.show();
                	break;
                case 4:
                	loadingDialog.dismiss();
                	sendOfflineFile(RingRecordFilePath.replaceAll(".raw", ".spx"),"audio");
                	break;
            }
        }
    };
    
    /** 设置Dialog的图片 */
    Handler volumeImagehandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(msg.what<=6)
            setVolumeImage(micImages[msg.what]);
            else
            	setVolumeImage(micImages[6]);
        }
    };
    /** 录音失败的提示 */
    ExtAudioRecorder.RecorderListener listener = new ExtAudioRecorder.RecorderListener() {
        @Override
        public void recordFailed(FailRecorder failRecorder) {
            if (failRecorder.getType() == FailRecorder.FailType.NO_PERMISSION) {
                Toast.makeText(ChatPullRefListActivity.this, "录音失败，可能是没有给权限", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(ChatPullRefListActivity.this, "发生了未知错误", Toast.LENGTH_SHORT).show();
            }
        }
    };
    
	private static ExecutorService LIMITED_TASK_EXECUTOR;
    static {
    	LIMITED_TASK_EXECUTOR = (ExecutorService) Executors.newFixedThreadPool(7); 
    }; 
    protected List<AsyncTask<Void, Void, Boolean>> mAsyncTasks = new ArrayList<AsyncTask<Void, Void, Boolean>>();
	protected void putAsyncTask(AsyncTask<Void, Void, Boolean> asyncTask) {
		mAsyncTasks.add(asyncTask.executeOnExecutor(LIMITED_TASK_EXECUTOR, null));
	}
	protected void clearAsyncTask() {
		Iterator<AsyncTask<Void, Void, Boolean>> iterator = mAsyncTasks
				.iterator();
		while (iterator.hasNext()) {
			AsyncTask<Void, Void, Boolean> asyncTask = iterator.next();
			if (asyncTask != null && !asyncTask.isCancelled()) {
				asyncTask.cancel(true);
			}
		}
		mAsyncTasks.clear();
	}
	private LoadingDialog loadingDialog;
    private Context mContext;
    
    
    private String jid = "";

//	@Override
//	public void onBackPressed() {//逻辑放到onKeyDown(int keyCode, KeyEvent event)中
//		Log.d("================20170507 ChatActivity onBackPressed================", "+++++++onBackPressed+++++++jid="+jid);
//			//通知ContactListPullRefListActivity更新局部 消息图章为0，不显示消息图章
//			Intent i = new Intent(ChatActivity.this,MainListActivity.class);//ContactListPullRefListActivity
//			i.putExtra("jid",jid);
//			startActivity(i);
//			finish();
//			return;
//	}
//    @SuppressLint("ShowToast")
    
    private ContactGroup mContact;
    private int type = 0;//0 contact,1 group
    private String uid;
    private String uuid;
    private String username;
    private String name;
    private String avatarpath;
    
    private String tagid;
    private String tagname;
    private String pic;
    
    private HeaderLayout mHeaderLayout;
    //网络状态start
	private View mNetErrorView;
	private TextView mConnect_status_info;
	private ImageView mConnect_status_btn;
//    private exPhoneCallListener myPhoneCallListener = null;
//    private TelephonyManager tm = null;
    //网络状态end
    
	  @Override
	  protected void onSaveInstanceState(Bundle outState) {
	      if (jid != null) {
	          outState.putString("KEY_CURRENT_JID", jid);
	      }
	      super.onSaveInstanceState(outState);
	  }
	  @Override
	  protected void onRestoreInstanceState(Bundle savedInstanceState) {
	  	jid = savedInstanceState.getString("KEY_CURRENT_JID");
	      super.onRestoreInstanceState(savedInstanceState);
	  }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
    	VMRuntime.getRuntime().setTargetHeapUtilization(TARGET_HEAP_UTILIZATION);
    	VMRuntime.getRuntime().setMinimumHeapSize(CWJ_HEAP_SIZE); //设置最小heap内存为6MB大小。当然对于内存吃紧来说还可以通过手动干涉GC去处理 
    	requestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chat);
        
        chatAdapterOffline = new ChatAdapterOffline(this);
        sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
        
        DisplayMetrics dm = DeviceUtils.getScreenPix(this);
        mScreenWidth = dm.widthPixels;
        mScreenHeight = dm.heightPixels;
//        if(savedInstanceState!=null)
//        	;
//        else
        if(getIntent().getStringExtra("jid")!=null
        		&& getIntent().getStringExtra("jid").length()!=0
        		&& !getIntent().getStringExtra("jid").equalsIgnoreCase("null"))
        jid = getIntent().getStringExtra("jid");
        
        if(jid!=null
        		&& jid.length()!=0
        		&& !jid.equalsIgnoreCase("null")){
        	mContact = new ContactGroup(jid);
        }
        

        
        type = getIntent().getIntExtra("type", 0);
        uid = getIntent().getStringExtra("uid");
        if(uid!=null
        		&& uid.length()!=0
        		&& !uid.equalsIgnoreCase("null")){
        }else
        	uid = "";
        uuid = getIntent().getStringExtra("uuid");
        if(uuid!=null
        		&& uuid.length()!=0
        		&& !uuid.equalsIgnoreCase("null")){
        }else
        	uuid = "";
        username = getIntent().getStringExtra("username");
        if(username!=null
        		&& username.length()!=0
        		&& !username.equalsIgnoreCase("null")){
        }else
        	username = "";
        name = getIntent().getStringExtra("name");
        if(name!=null
        		&& name.length()!=0
        		&& !name.equalsIgnoreCase("null")){
        }else
        	name = "";
        avatarpath = getIntent().getStringExtra("avatarpath");
        if(avatarpath!=null
        		&& avatarpath.length()!=0
        		&& !avatarpath.equalsIgnoreCase("null")){
        }else
        	avatarpath = "";
        tagid = getIntent().getStringExtra("tagid");
        if(tagid!=null
        		&& tagid.length()!=0
        		&& !tagid.equalsIgnoreCase("null")){
        }else
        	tagid = "";
        tagname = getIntent().getStringExtra("tagname");
        if(tagname!=null
        		&& tagname.length()!=0
        		&& !tagname.equalsIgnoreCase("null")){
        }else
        	tagname = "";
        pic = getIntent().getStringExtra("pic");
        if(pic!=null
        		&& pic.length()!=0
        		&& !pic.equalsIgnoreCase("null")){
        }else
        	pic = "";
        
        
    	Uri uri = getIntent().getData();//BeemChatManager 通知栏消息中点开聊天窗口
    	if(uri!=null){
    		mContact = new ContactGroup(uri);
    		type = mContact.getType();
    		uid = mContact.getUid();
    		tagid = mContact.getTagid();
    		username = mContact.getUsername();
    		tagname = mContact.getTagname();
    	}
    	
        
    	
    	AccountUser = sharedPrefs.getString("uidStr", "")+"@0";
    	Participant = mContact.getJID();
    	
        mContext = this;
        loadingDialog = new LoadingDialog(this);
//        initTitleBar("消息", "小Q", "", this);
        mHeaderLayout = (HeaderLayout) findViewById(R.id.title_bar);
        mHeaderLayout.init(HeaderStyle.TITLE_RIGHT_IMAGEBUTTON);
		mHeaderLayout.setTitleRightImageButton("消息", null,
				R.drawable.return2,
				new OnRightImageButtonClickListener());
		
        
        musicPlayManager = new MusicPlayManager();
        fh = new FinalHttp();
        inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
        sd = new SimpleDateFormat("MM-dd HH:mm");
        msgDao = new ChatMsgDao(this);
        staticFacesList = ExpressionUtil.initStaticFaces(this);
        voice_type = PreferencesUtils.getSharePreStr(this, Const.IM_VOICE_TPPE);
        
        
        micImages = getRecordAnimPic(getResources());
        AuditRecorderConfiguration configuration = new AuditRecorderConfiguration.Builder()
        .recorderListener(listener)
        .handler(volumeImagehandler)
        .uncompressed(true)
        .builder();

        recorder = new ExtAudioRecorder(configuration);
        
        
        jid = getIntent().getStringExtra("jid");
        if(jid==null || jid.equalsIgnoreCase("null"))
        	jid = "";
        Log.d("================20170507 ChatActivity onCreate================", "+++++++onCreate+++++++jid="+jid);
//        mNetErrorView = findViewById(R.id.net_status_bar_top);
//        mConnect_status_info = (TextView)mNetErrorView.findViewById(R.id.net_status_bar_info_top2);
//        mConnect_status_btn = (ImageView)mNetErrorView.findViewById(R.id.net_status_bar_btn);
//        mConnect_status_btn.setOnClickListener(this);
        duitangInfoAdapter = DuitangInfoAdapter.getInstance(this);
        mLoadingDialog = new FlippingLoadingDialog(this, "请求提交中");
        mNetErrorView = findViewById(R.id.net_status_bar_top2);
//        mNetErrorView = findViewById(R.id.net_status_title_bar);
        mConnect_status_info = (TextView)mNetErrorView.findViewById(R.id.net_status_bar_info_top2);
        mConnect_status_btn = (ImageView)mNetErrorView.findViewById(R.id.net_status_bar_btn);
        mConnect_status_btn.setOnClickListener(this);
        //初始化控件
        initViews();
        //初始化表情
        initViewPager();
        //初始化更多选项（即表情图标右侧"+"号内容）
        initAdd();
        //初始化数据
        initData();
        //初始化语音听写及合成部分
//        initSpeech();
        
//        mNetErrorView = findViewById(R.id.net_status_bar_top);
//        mConnect_status_info = (TextView)mNetErrorView.findViewById(R.id.net_status_bar_info_top2);
//        mConnect_status_btn = (ImageView)mNetErrorView.findViewById(R.id.net_status_bar_btn);
//        mConnect_status_btn.setOnClickListener(this);
        
	    IntentFilter mFilter = new IntentFilter();
	    mFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION); // 添加接收网络连接状态改变的Action
	    this.registerReceiver(mNetWorkReceiver, mFilter);
	    
        /* 添加自己实现的PhoneStateListener */
        myPhoneCallListener = new exPhoneCallListener();
       
       /* 取得电话服务 */
        tm =(TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
       
        /* 注册电话通信Listener */
        tm.listen(myPhoneCallListener,PhoneStateListener.LISTEN_CALL_STATE);
    }

//    private void initSpeech() {
//        speechRecognizerUtil = new SpeechRecognizerUtil(this);
//        speechRecognizerUtil.setRecoListener(this);
////        speechSynthesizerUtil = new SpeechSynthesizerUtil(this);
//    }

    /**
     * 初始化控件
     */
    private void initViews() {
//        mNetErrorView = findViewById(R.id.net_status_bar_top);
//        mConnect_status_info = (TextView)mNetErrorView.findViewById(R.id.net_status_bar_info_top2);
//        mConnect_status_btn = (ImageView)mNetErrorView.findViewById(R.id.net_status_bar_btn);
//        mConnect_status_btn.setOnClickListener(this);
        
        ll_playing = (LinearLayout) findViewById(R.id.ll_playing);
        tv_playing = (TextView) findViewById(R.id.tv_playing);

        mListView = (DropdownListView) findViewById(R.id.message_chat_listview);
//        SysUtils.setOverScrollMode(mListView);

        image_face = (ImageView) findViewById(R.id.image_face); //表情图标
        image_add = (ImageView) findViewById(R.id.image_add);//更多图标
        image_voice = (ImageView) findViewById(R.id.image_voice);//语音
        voice_text =  (TextView) findViewById(R.id.voice_text);//按住说话
        image_keyboard = (ImageView) findViewById(R.id.image_keyboard);//键盘文字输入
        chat_face_container = (LinearLayout) findViewById(R.id.chat_face_container);//表情布局
        chat_add_container = (LinearLayout) findViewById(R.id.chat_add_container);//更多

        mViewPager = (ViewPager) findViewById(R.id.face_viewpager);
        mViewPager.setOnPageChangeListener(new PageChange());
        //表情下小圆点
        mDotsLayout = (LinearLayout) findViewById(R.id.face_dots_container);
        input = (EditText) findViewById(R.id.input_sms);
//		mInputView = (EmoteInputView) findViewById(R.id.chat_eiv_inputview);
//		mEetTextDitorEditer = (EmoticonsEditText) findViewById(R.id.chat_textditor_eet_editer);
////		mEetTextDitorEditer = (EditText)findViewById(R.id.chat_textditor_eet_editer);
//		mEetTextDitorEditer.addTextChangedListener(this);
//		mEetTextDitorEditer.setOnTouchListener(this);
//		
//		mInputView.setEditText(mEetTextDitorEditer);
		
        send = (TextView) findViewById(R.id.send_sms);
        input.setOnClickListener(this);
        input.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            	voice_text.setVisibility(View.GONE);
            	input.setVisibility(View.VISIBLE);
//                image_voice.setVisibility(View.GONE);
                image_keyboard.setVisibility(View.GONE);
                if (s.length() > 0) {
                    send.setVisibility(View.VISIBLE);
                    image_voice.setVisibility(View.GONE);
                } else {
                    send.setVisibility(View.GONE);
                    image_voice.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });

        image_face.setOnClickListener(this);//表情按钮
        image_add.setOnClickListener(this);//更多按钮
        image_voice.setOnClickListener(this);//语音按钮
        image_keyboard.setOnClickListener(this);//键盘文字输入按钮
//        voice_text.setOnClickListener(this);
        send.setOnClickListener(this); // 发送

        mListView.setOnRefreshListenerHead(this);
        mListView.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View arg0, MotionEvent arg1) {
                if (arg1.getAction() == MotionEvent.ACTION_DOWN) {
                    if (chat_face_container.getVisibility() == View.VISIBLE) {
                        chat_face_container.setVisibility(View.GONE);
                    }
                    if (chat_add_container.getVisibility() == View.VISIBLE) {
                        chat_add_container.setVisibility(View.GONE);
                    }
                    hideSoftInputView();
                }
                return false;
            }
        });
        
        //voice_text start
        initAudioRecordView();
        voice_text.setOnTouchListener(new View.OnTouchListener() {

    		@Override
    		public boolean onTouch(View v, MotionEvent event) {
//    			if (CommonUtils.isFastDoubleClick())
//    				return false;
    			
    			String str = new Random().nextInt()+"";
    			int action = event.getAction();

    			int[] location = new int[2];
    			voice_text.getLocationInWindow(location); // 获取在当前窗口内的绝对坐标
    			int btn_rc_Y = location[1];
    			int btn_rc_X = location[0];
    			int[] del_location = new int[2];
    			del_re.getLocationInWindow(del_location);
    			int del_Y = del_location[1];
    			int del_x = del_location[0];
    			
    			Log.e("※※※※※####语音20140808语音####※※※※※", "※※####语音20140808语音####※※btn_rc_Y="+btn_rc_Y
    					+";btn_rc_X="+btn_rc_X
    					+";del_Y="+del_Y
    					+";del_x="+del_x
    					+";event.getY()="+event.getY()
    					+";event.getX()="+event.getX());
    			
    			switch (action) {
    			case MotionEvent.ACTION_CANCEL:
    				v.setBackgroundResource(R.drawable.transparent);
					voice_rcd_hint_rcding.setVisibility(View.GONE);
					stop();
					endVoiceT = SystemClock.currentThreadTimeMillis();
					flag = 1;
					if (recodeTime < MIX_TIME){
						isShosrt = true;
						voice_rcd_hint_loading.setVisibility(View.GONE);
						voice_rcd_hint_rcding.setVisibility(View.GONE);
						voice_rcd_hint_tooshort.setVisibility(View.VISIBLE);
						voice_rcd_hint_toolong.setVisibility(View.GONE);
						volumeImagehandler.postDelayed(new Runnable() {
							public void run() {
								voice_rcd_hint_tooshort
										.setVisibility(View.GONE);
								rcChat_popup.setVisibility(View.GONE);
								isShosrt = false;
							}
						}, 500);
						return false;
					}else if (recodeTime >= MAX_TIME && MAX_TIME != 0){
						isShosrt = true;
						voice_rcd_hint_loading.setVisibility(View.GONE);
						voice_rcd_hint_rcding.setVisibility(View.GONE);
						voice_rcd_hint_tooshort.setVisibility(View.GONE);
						voice_rcd_hint_toolong.setVisibility(View.VISIBLE);
						volumeImagehandler.postDelayed(new Runnable() {
							public void run() {
								voice_rcd_hint_toolong
										.setVisibility(View.GONE);
								rcChat_popup.setVisibility(View.GONE);
								isShosrt = false;
							}
						}, 500);
						return false;
					}
					//发送
					rcChat_popup.setVisibility(View.GONE);
					if (event.getY() > 0 && event.getX() > btn_rc_X) {
					if (MAX_TIME>=recodeTime && recodeTime >= MIX_TIME)
					if(RingRecordFilePath!=null && !RingRecordFilePath.equals(""))
//						sendOfflineFile(RingRecordFilePath,"audio");
//						;
						decode();
					}else{
						if(RingRecordFilePath!=null && !RingRecordFilePath.equals(""))
							scanOldFile();
//							;
						}
    				Log.d("onTouchEvent action:ACTION_UP", "---onTouchEvent action:ACTION_UP");
					
    				break;
    			case MotionEvent.ACTION_UP:
    				v.setBackgroundResource(R.drawable.transparent);
					voice_rcd_hint_rcding.setVisibility(View.GONE);
					stop();
					endVoiceT = SystemClock.currentThreadTimeMillis();
					flag = 1;
					if (recodeTime < MIX_TIME){
						isShosrt = true;
						voice_rcd_hint_loading.setVisibility(View.GONE);
						voice_rcd_hint_rcding.setVisibility(View.GONE);
						voice_rcd_hint_tooshort.setVisibility(View.VISIBLE);
						voice_rcd_hint_toolong.setVisibility(View.GONE);
						volumeImagehandler.postDelayed(new Runnable() {
							public void run() {
								voice_rcd_hint_tooshort
										.setVisibility(View.GONE);
								rcChat_popup.setVisibility(View.GONE);
								isShosrt = false;
							}
						}, 500);
						return false;
					}else if (recodeTime >= MAX_TIME && MAX_TIME != 0){
						isShosrt = true;
						voice_rcd_hint_loading.setVisibility(View.GONE);
						voice_rcd_hint_rcding.setVisibility(View.GONE);
						voice_rcd_hint_tooshort.setVisibility(View.GONE);
						voice_rcd_hint_toolong.setVisibility(View.VISIBLE);
						volumeImagehandler.postDelayed(new Runnable() {
							public void run() {
								voice_rcd_hint_toolong
										.setVisibility(View.GONE);
								rcChat_popup.setVisibility(View.GONE);
								isShosrt = false;
							}
						}, 500);
						return false;
					}
					//发送
					rcChat_popup.setVisibility(View.GONE);
					if (event.getY() > 0 && event.getX() > btn_rc_X) {
					if (MAX_TIME>=recodeTime && recodeTime >= MIX_TIME)
					if(RingRecordFilePath!=null && !RingRecordFilePath.equals(""))
//						sendOfflineFile(RingRecordFilePath,"audio");
//						;
						decode();
					}else{
						if(RingRecordFilePath!=null && !RingRecordFilePath.equals(""))
						scanOldFile();
//							;
					}
    				Log.d("onTouchEvent action:ACTION_UP", "---onTouchEvent action:ACTION_UP");
    				break;
    			case MotionEvent.ACTION_DOWN:
//    				if (event.getY() > btn_rc_Y && event.getX() > btn_rc_X) {//判断手势按下的位置是否是语音录制按钮的范围内
    				if (event.getY() > 0 && event.getX() > btn_rc_X) {
    					Log.e("※※※※※####语音20140808语音范围内####※※※※※", "※※####语音20140808语音范围内####※※");
					v.setBackgroundResource(R.drawable.hold_to_talk_normal);
					rcChat_popup.setVisibility(View.VISIBLE);
					voice_rcd_hint_loading.setVisibility(View.VISIBLE);
					voice_rcd_hint_rcding.setVisibility(View.GONE);
					voice_rcd_hint_tooshort.setVisibility(View.GONE);
					voice_rcd_hint_toolong.setVisibility(View.GONE);
					volumeImagehandler.postDelayed(new Runnable() {
						public void run() {
							if (!isShosrt) {
								voice_rcd_hint_loading.setVisibility(View.GONE);
								voice_rcd_hint_rcding
										.setVisibility(View.VISIBLE);
							}
						}
					}, 300);
					img1.setVisibility(View.VISIBLE);
					del_re.setVisibility(View.GONE);
					startVoiceT = SystemClock.currentThreadTimeMillis();
					RingRecordFilePath = getAmrPath();
					start(RingRecordFilePath);
//    				}else if (event.getY() < btn_rc_Y) {//手势按下的位置不在语音录制按钮的范围内
    				}else if (event.getY() < 0) {//手势按下的位置不在语音录制按钮的范围内
    					Log.e("※※※※※####语音20140808语音不在范围内####※※※※※", "※※####语音20140808语音不在范围内####※※");
    					System.out.println("5");
//    					Animation mLitteAnimation = AnimationUtils.loadAnimation(mContext,
//    							R.anim.cancel_rc);
//    					Animation mBigAnimation = AnimationUtils.loadAnimation(mContext,
//    							R.anim.cancel_rc2);
    					img1.setVisibility(View.GONE);
    					del_re.setVisibility(View.VISIBLE);
//    					del_re.setBackgroundResource(R.drawable.voice_rcd_cancel_bg);
//    					if (event.getY() >= del_Y
//    							&& event.getY() <= del_Y + del_re.getHeight()
//    							&& event.getX() >= del_x
//    							&& event.getX() <= del_x + del_re.getWidth()) {
    						del_re.setBackgroundResource(R.drawable.voice_rcd_cancel_bg_focused);
//    						sc_img1.startAnimation(mLitteAnimation);
//    						sc_img1.startAnimation(mBigAnimation);
//    					}
    				}else {
    					Log.e("※※※※※####语音20140808语音其它####※※※※※", "※※####语音20140808语音其它####※※");
    					img1.setVisibility(View.VISIBLE);
    					del_re.setVisibility(View.GONE);
    					del_re.setBackgroundResource(0);
    				}
    				break;
				default:
					if (event.getY() > 0 && event.getX() > btn_rc_X) {
						Log.e("※※※※※####语音20140808语音范围内2####※※※※※", "※※####语音20140808语音范围内2####※※");
    					img1.setVisibility(View.VISIBLE);
    					del_re.setVisibility(View.GONE);
    					del_re.setBackgroundResource(0);
					}else if (event.getY() < 0) {//手势按下的位置不在语音录制按钮的范围内
    					Log.e("※※※※※####语音20140808语音不在范围内####※※※※※", "※※####语音20140808语音不在范围内####※※");
    					System.out.println("5");
//    					Animation mLitteAnimation = AnimationUtils.loadAnimation(mContext,
//    							R.anim.cancel_rc);
//    					Animation mBigAnimation = AnimationUtils.loadAnimation(mContext,
//    							R.anim.cancel_rc2);
    					Animation mLitteAnimation = AnimationUtils.loadAnimation(mContext,
						R.anim.zoom_enter);
    					Animation mBigAnimation = AnimationUtils.loadAnimation(mContext,
						R.anim.zoom_exit);
    					img1.setVisibility(View.GONE);
    					del_re.setVisibility(View.VISIBLE);
//    					del_re.setBackgroundResource(R.drawable.voice_rcd_cancel_bg);
//    					if (event.getY() >= del_Y
//    							&& event.getY() <= del_Y + del_re.getHeight()
//    							&& event.getX() >= del_x
//    							&& event.getX() <= del_x + del_re.getWidth()) {
    						del_re.setBackgroundResource(R.drawable.voice_rcd_cancel_bg_focused);
    						sc_img1.startAnimation(mLitteAnimation);
    						sc_img1.startAnimation(mBigAnimation);
//    					}
    				}else {
    					Log.e("※※※※※####语音20140808语音其它####※※※※※", "※※####语音20140808语音其它####※※");
    					img1.setVisibility(View.VISIBLE);
    					del_re.setVisibility(View.GONE);
    					del_re.setBackgroundResource(0);
    				}
					break;
    			}

    			return true;
    		}
    	});
        //voice_text end
    }
    
	public void initAudioRecordView(){
		volume = (ImageView) this.findViewById(R.id.volume);
		rcChat_popup = this.findViewById(R.id.rcChat_popup);
		img1 = (ImageView) this.findViewById(R.id.img1);
		sc_img1 = (ImageView) this.findViewById(R.id.sc_img1);
		del_re = (LinearLayout) this.findViewById(R.id.del_re);
		voice_rcd_hint_rcding = (LinearLayout) this
				.findViewById(R.id.voice_rcd_hint_rcding);
		voice_rcd_hint_loading = (LinearLayout) this
				.findViewById(R.id.voice_rcd_hint_loading);
		voice_rcd_hint_tooshort = (LinearLayout) this
				.findViewById(R.id.voice_rcd_hint_tooshort);
		voice_rcd_hint_toolong = (LinearLayout) this
		.findViewById(R.id.voice_rcd_hint_toolong);
//		mr = new AudioRecorder();
//		mr = new ARecorder();
//		mr.initRecorder();
		
//		initMediaplayer();
//		/* 监听播放是否完成 */
//		mMediaPlayer.setOnCompletionListener(this);
	}
	private static final int POLL_INTERVAL = 300;

	private Runnable mSleepTask = new Runnable() {
		public void run() {
			stop();
		}
	};
	private Runnable mPollTask = new Runnable() {
		public void run() {
			if (recodeTime >= MAX_TIME && MAX_TIME != 0){//录音超过15秒自动停止
				stop();
			}else{
//				double amp = mr.getAmplitude();
//				updateDisplay(amp);
				recodeTime += 0.2;
				volumeImagehandler.postDelayed(mPollTask, POLL_INTERVAL);
			}
		}
	};

	private void start(String name) {
		recodeTime = 0.0f;
		try{
////		mr.start(name);
//		mr.mIsRecording = true;
//		mr.mRecorder.startRecording();
////		 * mRawFile = getFile("raw");
//		mr.startBufferedWrite(new File(name));
			// 设置输出文件
            recorder.setOutputFile(name);
            recorder.prepare();
            recorder.start();
		}catch(Exception e){}
		
		volumeImagehandler.postDelayed(mPollTask, POLL_INTERVAL);
	}

	private void stop() {
		volumeImagehandler.removeCallbacks(mSleepTask);
		volumeImagehandler.removeCallbacks(mPollTask);
		try{
////		mr.stop();
//			mr.mIsRecording = false;
//			mr.mRecorder.stop();
//			mr.mRecorder.release();
//			mr.mRecorder = null;
			recorder.reset();

			//jspeex 压缩与解压缩需要放到thread中处理 start
//		JSEncode jsencode = new JSEncode();
//		jsencode.initEncoder();
//		String mRawFile = RingRecordFilePath;
//		String mEncodedFile = RingRecordFilePath.replaceAll(".raw", ".spx");
//		try {
//			jsencode.encodeFile(new File(mRawFile), new File(mEncodedFile));
//		} catch (IOException e) {
//			e.printStackTrace();
//		}
//		JSpeexDec decoder = new JSpeexDec();
//		String destPath = RingRecordFilePath.replaceAll(".raw", "_decode.raw");
//		decoder.decode(new File(mEncodedFile), new File (destPath));
		//jspeex 压缩与解压缩需要放到thread中处理 end
//			decode();
		}catch(Exception e){
			e.printStackTrace();
		}
		volume.setImageResource(R.drawable.amp1);
	}
	
	private void decode() {

		putAsyncTask(new AsyncTask<Void, Void, Boolean>() {

			@Override
			protected void onPreExecute() {
				super.onPreExecute();
//				showLoadingDialog("正在加载,请稍后...");
//				loadingDialog.show();
				mHandler.sendEmptyMessage(3);
			}

			@Override
			protected Boolean doInBackground(Void... params) {
//				initContactList();
				try{
					//jspeex 压缩与解压缩需要放到thread中处理 start
					JSEncode jsencode = new JSEncode();
					jsencode.initEncoder();
					String mRawFile = RingRecordFilePath;
					String mEncodedFile = RingRecordFilePath.replaceAll(".raw", ".spx");
					try {
						jsencode.encodeFile(new File(mRawFile), new File(mEncodedFile));
					} catch (IOException e) {
						e.printStackTrace();
					}
//					JSpeexDec decoder = new JSpeexDec();
//					String destPath = RingRecordFilePath.replaceAll(".raw", "_decode.raw");
//					decoder.decode(new File(mEncodedFile), new File (destPath));
					//jspeex 压缩与解压缩需要放到thread中处理 end
				}catch(Exception e){
					e.printStackTrace();
				}
				return true;
			}

			@Override
			protected void onPostExecute(Boolean result) {
				super.onPostExecute(result);
//				dismissLoadingDialog();
//				loadingDialog.dismiss();
				mHandler.sendEmptyMessage(4);
				if (!result) {
//					showCustomToast("数据加载失败...");
//					mHandler2.sendEmptyMessage(3);
				} else {
//					mHandler2.sendEmptyMessage(0);
				}
			}

		});
	}
	
	private void updateDisplay(double signalEMA) {
		
		switch ((int) signalEMA) {
		case 0:
		case 1:
			volume.setImageResource(R.drawable.amp1);
			break;
		case 2:
		case 3:
			volume.setImageResource(R.drawable.amp2);
			
			break;
		case 4:
		case 5:
			volume.setImageResource(R.drawable.amp3);
			break;
		case 6:
		case 7:
			volume.setImageResource(R.drawable.amp4);
			break;
		case 8:
		case 9:
			volume.setImageResource(R.drawable.amp5);
			break;
		case 10:
		case 11:
			volume.setImageResource(R.drawable.amp6);
			break;
		default:
			volume.setImageResource(R.drawable.amp7);
			break;
		}
	}

	//获取文件手机路径
	private String getAmrPath(){
		File file = new File(setMkdir(PHOTOPATH2),getRingRecordFileName());
		return file.getAbsolutePath();
	}
	//删除老文件
	void scanOldFile(){

//		File file = new File(RingRecordFilePath);
//		if(file.exists()){
//			file.delete();
//		}
	}
    /** 
     * 保存文件文件到目录 
     * @param context 
     * @return  文件保存的目录 
     */  
    public String setMkdir(String myrelativefilepath)  
    {  
        String filePath;  
        if(checkSDCard())  
        {  
//            filePath = Environment.getExternalStorageDirectory()+File.separator+"myfilepath"; 
            filePath = Environment.getExternalStorageDirectory()+File.separator+myrelativefilepath+File.separator;
        }else{  
//            filePath = context.getCacheDir().getAbsolutePath()+File.separator+"myfilepath";  
            filePath = this.getCacheDir().getAbsolutePath()+File.separator+myrelativefilepath+File.separator; 
        }  
        File file = new File(filePath);  
        if(!file.exists())  
        {  
            boolean b = file.mkdirs();  
//            Log.e("file", "文件不存在  创建文件    "+b);  
        }else{  
//            Log.e("file", "文件存在");  
        }  
        return filePath;  
    } 
    /** 
     * 检验SDcard状态 
     * @return boolean 
     */  
    public boolean checkSDCard()  
    {  
        if(android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))  
        {  
            return true;  
        }else{  
            return false;  
        }  
    }
    
	
    public void initAdd() {
        tv_weather = (TextView) findViewById(R.id.tv_weather);
        tv_xingzuo = (TextView) findViewById(R.id.tv_xingzuo);
        tv_joke = (TextView) findViewById(R.id.tv_joke);
        tv_loc = (TextView) findViewById(R.id.tv_loc);
        tv_gg = (TextView) findViewById(R.id.tv_gg);
        tv_mm = (TextView) findViewById(R.id.tv_mm);
        tv_music = (TextView) findViewById(R.id.tv_music);

        tv_weather.setOnClickListener(this);
        tv_xingzuo.setOnClickListener(this);
        tv_joke.setOnClickListener(this);
        tv_loc.setOnClickListener(this);
        tv_gg.setOnClickListener(this);
        tv_mm.setOnClickListener(this);
        tv_music.setOnClickListener(this);
    }

    public void initData() {
        offset = 0;
        listMsg = msgDao.queryMsg(from, to, offset);
        offset = listMsg.size();
//        mLvAdapter = new ChatAdapter(this, listMsg, this);
//        mListView.setAdapter(mLvAdapter);
        
        mAdapter = new StaggeredAdapter(this);
        mListView.setAdapter(mAdapter);
        
        mListView.setSelection(listMsg.size());
        
//        getChatPullRefList();
    }

    /**
     * Change the displayed chat.
     * @param contact the targeted contact of the new chat
     * @throws RemoteException If a Binder remote-invocation error occurred.
     */
    private void changeCurrentChat() throws RemoteException {
//		if (mChat != null) {
//		    mChat.setOpen(false);
//		    Log.e("※※※※※20170810(000)※※※※※", "mChat.setOpen(false)");
//		    mChat.removeMessageListener(mMessageListener);
//		}

		try{
			mChat = null;
//		    mChat = mChatManager.getChat(mContact);
//			if (mChat == null) {
//				if(mChatManager!=null)
			    mChat = mChatManager.createChat(mContact, null);//mMessageListener
//				if(mChat!=null)
			    mChat.setOpen(true);
			    Log.e("※※※※※20170810(111)※※※※※", "mChat.setOpen(true)");
			    mChat.addMessageListener(mMessageListener);
			    mChatManager.deleteChatNotification(mChat);//删除notification
//			}
//			mChat.setOpen(true);
//			Log.e("※※※※※20170810(222)※※※※※", "mChat.setOpen(true)");
//			mChat.addMessageListener(mMessageListener);
//			mChatManager.deleteChatNotification(mChat);//删除notification
		}catch(Exception e){
			e.printStackTrace();
		}
		playRegisteredTranscript();//
    }
    /**
     * Get all messages from the current chat and refresh the activity with them.
     * @throws RemoteException If a Binder remote-invocation error occurred.
     */
	private List<com.stb.core.chat.Message> temp1 = null;
	private static int pageSize = 100;//每页显示条数
    private void playRegisteredTranscript() throws RemoteException {//第一次进入Chat聊天界面初始化时，查询本地sqlite中存储的聊天记录
//		mListMessages.clear();
		if (mChat != null) {
			//记录总数
			TotalCount = (int)mChat.getAllMessagesCount();
			//总页码
			pageCount = TotalCount%pageSize==0? TotalCount/pageSize-1 : TotalCount/pageSize;
			Log.e("===============20140720=================", "++++++++++++++20140720TotalCount="+TotalCount+",pageCount="+pageCount+"+++++++++++++");
			temp1 = mChat.getMessagesByPageIndex(pageSize, 0);//HISTORY_MAX_SIZE 1    
			if(temp1!=null && temp1.size()!=0){
			    msgList = convertMessagesList(temp1);
			    duitangs2.addAll(msgList);
			    temp1 = null;
			    msgList = null;
	//		    onLoadMore();
			    onAddMessage();
			}
		}
    }
    
    private void preLoadplayRegisteredTranscript(){//如果断开了连接（无论是服务器宕机还是客户端本身问题）第一次进入Chat聊天界面初始化时，查询本地sqlite中存储的聊天记录
//    	AccountUser = sharedPrefs.getString("uidStr", "")+"@0";
//    	Participant = mContact.getJID();
    	TotalCount = (int)chatAdapterOffline.getAllMessagesCount(AccountUser, Participant);
    	pageCount = TotalCount%pageSize==0? TotalCount/pageSize-1 : TotalCount/pageSize;
    	temp1 = chatAdapterOffline.getMessagesByPageIndex(AccountUser, Participant,pageSize, 0);//HISTORY_MAX_SIZE 1  
		if(temp1!=null && temp1.size()!=0){
		    msgList = convertMessagesList(temp1);
		    duitangs2.addAll(msgList);
		    temp1 = null;
		    msgList = null;
//		    onLoadMore();
		    onAddMessage();
		}
    }
    /**
     * 初始化表情
     */
    private void initViewPager() {
        int pagesize = ExpressionUtil.getPagerCount(staticFacesList.size(), columns, rows);
        Log.d("======pageSize======", pagesize+"");
        // 获取页数
        for (int i = 0; i < pagesize; i++) {
            views.add(ExpressionUtil.viewPagerItem(this, i, staticFacesList, columns, rows, input));
            LayoutParams params = new LayoutParams(16, 16);
            mDotsLayout.addView(dotsItem(i), params);
        }
        FaceVPAdapter mVpAdapter = new FaceVPAdapter(views);
        mViewPager.setAdapter(mVpAdapter);
        mDotsLayout.getChildAt(0).setSelected(true);
    }

    /**
     * 表情页切换时，底部小圆点
     *
     * @param position
     * @return
     */
    private ImageView dotsItem(int position) {
        View layout = inflater.inflate(R.layout.dot_image, null);
        ImageView iv = (ImageView) layout.findViewById(R.id.face_dot);
        iv.setId(position);
        return iv;
    }


    @Override
    public void onClick(View arg0) {
        super.onClick(arg0);
        switch (arg0.getId()) {
            //网络设置
            case R.id.net_status_bar_btn:
            	setNetworkMethod(this);
            	break;
            case R.id.send_sms://发送
                String content = input.getText().toString();
                if (TextUtils.isEmpty(content)) {
                    return;
                }
                sendMsgText(content, true);
                break;
            case R.id.input_sms://点击输入框
                if (chat_face_container.getVisibility() == View.VISIBLE) {
                    chat_face_container.setVisibility(View.GONE);
                }
                if (chat_add_container.getVisibility() == View.VISIBLE) {
                    chat_add_container.setVisibility(View.GONE);
                }
                break;
            case R.id.image_face://点击表情按钮
                hideSoftInputView();//隐藏软键盘
                if (chat_add_container.getVisibility() == View.VISIBLE) {
                    chat_add_container.setVisibility(View.GONE);
                }
                if (chat_face_container.getVisibility() == View.GONE) {
                    chat_face_container.setVisibility(View.VISIBLE);
                } else {
                    chat_face_container.setVisibility(View.GONE);
                }
                break;
            case R.id.image_add://点击加号按钮
                hideSoftInputView();//隐藏软键盘
                if (chat_face_container.getVisibility() == View.VISIBLE) {
                    chat_face_container.setVisibility(View.GONE);
                }
                if (chat_add_container.getVisibility() == View.GONE) {
                    chat_add_container.setVisibility(View.VISIBLE);
                } else {
                    chat_add_container.setVisibility(View.GONE);
                }
                break;
            case R.id.image_voice://点击语音按钮
            	voice_text.setVisibility(View.VISIBLE);
            	input.setVisibility(View.GONE);
                image_voice.setVisibility(View.GONE);
                image_keyboard.setVisibility(View.VISIBLE);
                if (!TextUtils.isEmpty(voice_type) && voice_type.equals("1")) {//以语音形式发送
//                    speechRecognizerUtil.say(input, false);
                } else {//以文本形式发送
//                    speechRecognizerUtil.say(input, true);
                }
                break;
//            case R.id.voice_text://长按录音
//            	break;
            case R.id.image_keyboard://点击键盘文字输入按钮
            	voice_text.setVisibility(View.GONE);
            	input.setVisibility(View.VISIBLE);
                image_voice.setVisibility(View.VISIBLE);
                image_keyboard.setVisibility(View.GONE);
                break;
            case R.id.tv_weather://选择本地照片发送
//                sendMsgText(PreferencesUtils.getSharePreStr(this, Const.CITY) + "天气", true);
                GalleryHelper.openGallerySingle(ChatPullRefListActivity.this, true, new GalleryImageLoader());
                if (chat_add_container.getVisibility() == View.VISIBLE) {
                    chat_add_container.setVisibility(View.GONE);
                }
                break;
            case R.id.tv_xingzuo://拍摄照片发送
//                input.setText("星座#");
//                input.setSelection(input.getText().toString().length());//光标移至最后
//                changeList(Const.MSG_TYPE_TEXT, "请输入星座#您的星座查询");
//                chat_add_container.setVisibility(View.GONE);
//                showSoftInputView(input);
            	takePhotoAction();
//            	Intent intent = new Intent(ChatPullRefListActivity.this, PhotoTakeActivity.class);
//				startActivityForResult(intent, GalleryHelper.GALLERY_RESULT_SUCCESS);
            	if (chat_add_container.getVisibility() == View.VISIBLE) {
                    chat_add_container.setVisibility(View.GONE);
                }
                break;
            case R.id.tv_joke://发送定位地图
//                sendMsgText("笑话", true);
                Intent intent3 = new Intent(ChatPullRefListActivity.this, LocationDemo.class);
				startActivityForResult(intent3, 3);
                break;
            case R.id.tv_loc://发送本地视频文件
//                sendMsgText("位置", false);
//                String lat = PreferencesUtils.getSharePreStr(this, Const.LOCTION);//经纬度
//                if (TextUtils.isEmpty(lat)) {
//                    lat = "116.404,39.915";//北京
//                }
//                changeList(Const.MSG_TYPE_LOCATION, Const.LOCATION_URL_S + lat + "&markers=|" + lat + "&markerStyles=l,A,0xFF0000");//传入地图（图片）路径
//                
//                Intent intent4 = new Intent();  
                Intent intent4 = new Intent(Intent.ACTION_GET_CONTENT);
                /* 开启Pictures画面Type设定为image */  
                //intent.setType("image/*");  
                // intent.setType("audio/*"); //选择音频  
                 intent4.setType("video/*"); //选择视频 （mp4 3gp 是android支持的视频格式）  
          
                // intent.setType("video/*;image/*");//同时选择视频和图片  
          
                /* 使用Intent.ACTION_GET_CONTENT这个Action */  
//                intent4.setAction(Intent.ACTION_GET_CONTENT);  
                intent4.addCategory(Intent.CATEGORY_OPENABLE);
                /* 取得相片后返回本画面 */  
                startActivityForResult(intent4, REQUEST_VIDEO_CODE); 
//            	showCustomToast("功能建设中...");
                
                
//            	Intent intent4 = new Intent(Intent.ACTION_GET_CONTENT);
//
//            	intent4.setType("vedio/*");//选取所有的视频类型 *有mp4、3gp、avi等
//
//            	startActivityForResult(intent4, REQUEST_VIDEO_CODE);
                
                break;
            case R.id.tv_gg://文件
//                sendMsgText("帅哥", true);
				Intent intent2 = new Intent(ChatPullRefListActivity.this, FileActivity.class);
				startActivityForResult(intent2, 2);
                break;
            case R.id.tv_mm:
                sendMsgText("美女", true);
                break;
            case R.id.tv_music://礼物
//                input.setText("歌曲##");
//                input.setSelection(input.getText().toString().length() - 1);
//                changeList(Const.MSG_TYPE_TEXT, "请输入：歌曲#歌曲名#演唱者");
//                chat_add_container.setVisibility(View.GONE);
//                showSoftInputView(input);
            	showCustomToast("功能建设中...");
                break;
        }
    }

    /**
     * 执行发送消息 文本类型
     * isReqApi 是否调用api回答问题
     *
     * @param content
     */
    void sendMsgText(String content, boolean isReqApi) {
        if (content.endsWith("##")) {
            ToastUtil.showToast(this, "输入有误");
            return;
        }
        Msg msg = getChatInfoTo(content, Const.MSG_TYPE_TEXT);
        msg.setMsgId(msgDao.insert(msg));
        listMsg.add(msg);
        offset = listMsg.size();
        mAdapter.notifyDataSetChanged();
        input.setText("");
//        sendMsgIQ();
        sendMsgIQ_fuc2(content);
        if (isReqApi) getFromMsg(Const.MSG_TYPE_TEXT, content);
    }

    /**
     * 执行发送消息 图片类型
     */
    void sendMsgImg(String imgpath) {
        Msg msg = getChatInfoTo(imgpath, Const.MSG_TYPE_IMG);
        msg.setMsgId(msgDao.insert(msg));
        listMsg.add(msg);
        offset = listMsg.size();
        mAdapter.notifyDataSetChanged();

    }

    /**
     * 执行发送消息 位置类型
     *
     * @param content
     */
    void sendMsgLocation(String content) {
        Msg msg = getChatInfoTo(content, Const.MSG_TYPE_LOCATION);
        msg.setMsgId(msgDao.insert(msg));
        listMsg.add(msg);
        offset = listMsg.size();
        mAdapter.notifyDataSetChanged();
    }

    /**
     * 发送语音
     *
     * @param content
     */
    void sendMsgVoice(String content) {
        String[] _content = content.split(Const.SPILT);
        Msg msg = getChatInfoTo(content, Const.MSG_TYPE_VOICE);
        msg.setMsgId(msgDao.insert(msg));
        listMsg.add(msg);
        offset = listMsg.size();
        mAdapter.notifyDataSetChanged();
        getFromMsg(Const.MSG_TYPE_TEXT, _content[1]);
    }

    /**
     * 发送的信息
     * from为收到的消息，to为自己发送的消息
     *
     * @return
     */
    private Msg getChatInfoTo(String message, int msgtype) {
        String time = sd.format(new Date());
        Msg msg = new Msg();
        msg.setFromUser(from);
        msg.setToUser(to);
        msg.setType(msgtype);
        msg.setIsComing(1);
        msg.setContent(message);
        msg.setDate(time);
        return msg;
    }

    /**
     * 获取结果
     *
     * @param msgtype
     * @param info
     */
    private void getFromMsg(final int msgtype, String info) {
        if (info.startsWith("星座#") && info.length() > 3) {
            getResponse(msgtype, info.split("#")[1] + "运势");
        } else if (info.startsWith("歌曲#") && info.split("#").length == 3) {
            String[] _info = info.split("#");
            if (TextUtils.isEmpty(_info[1]) || TextUtils.isEmpty(_info[2])) {
                ToastUtil.showToast(this, "输入有误");
                return;
            }
            getMusic(_info[1], _info[2]);
        } else {
            getResponse(msgtype, info);
        }
    }

    /**
     * 调用机器人api获取回答结果
     *
     * @param msgtype
     * @param info
     */
    void getResponse(final int msgtype, String info) {
        ajaxParams=new AjaxParams();
        ajaxParams.put("key",Const.ROBOT_KEY);
        ajaxParams.put("info",info);
        fh.post(Const.ROBOT_URL,ajaxParams, new AjaxCallBack<Object>() {
            @Override
            public void onSuccess(Object o) {
                super.onSuccess(o);
                LogUtil.e("response>>" + o);
                Answer answer = PraseUtil.praseMsgText((String) o);
                String responeContent;
                if (answer == null) {
                    responeContent = "网络错误";
                    changeList(msgtype, responeContent);
                } else {
                    switch (answer.getCode()) {
                        case 40001://参数key错误
                        case 40002://请求内容info为空
                        case 40004://当天请求次数已使用完
                        case 40007://数据格式异常
                        case 100000://文本
                            responeContent = answer.getText();
                            changeList(msgtype, responeContent);
                            break;
                        case 200000://链接
                            responeContent = answer.getText() + answer.getUrl();
                            changeList(msgtype, responeContent);
                            break;
                        case 302000://新闻
                        case 308000://菜谱
                            responeContent=answer.getJsoninfo();
                            changeList(Const.MSG_TYPE_LIST, responeContent);
                            break;
                    }
                }
            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                super.onFailure(t, errorNo, strMsg);
                changeList(msgtype, "网络连接失败");
            }
        });
    }

    /**
     * 获取音乐链接
     *
     * @param name
     * @param author
     */
    void getMusic(final String name, final String author) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                Music music = MusicSearchUtil.searchMusic(name, author);
                Message msg = new Message();
                msg.what = 2;
                msg.obj = music;
                mHandler.sendMessage(msg);
            }
        }).start();
    }

    /**
     * 刷新数据
     *
     * @param msgtype
     * @param responeContent
     */
    private void changeList(int msgtype, String responeContent) {
        Msg msg = new Msg();
        msg.setIsComing(0);
        msg.setContent(responeContent);
        msg.setType(msgtype);
        msg.setFromUser(from);
        msg.setToUser(to);
        msg.setDate(sd.format(new Date()));
        msg.setMsgId(msgDao.insert(msg));
        listMsg.add(msg);
        offset = listMsg.size();
        if(mAdapter!=null)
        mAdapter.notifyDataSetChanged();
        if (msg.getType()==Const.MSG_TYPE_TEXT) {
            String speech_type = PreferencesUtils.getSharePreStr(this, Const.IM_SPEECH_TPPE);
            if (!TextUtils.isEmpty(speech_type) && speech_type.equals("1")) {
//                speechSynthesizerUtil.speech(msg.getContent());
            }
        }

    }

    @Override
    public void click(int position) {//点击
        Msg msg = listMsg.get(position);
        switch (msg.getType()) {
            case Const.MSG_TYPE_TEXT://文本
                break;
            case Const.MSG_TYPE_IMG://图片
                break;
            case Const.MSG_TYPE_LOCATION://位置
                Intent intent = new Intent(this, ImgPreviewActivity.class);
                intent.putExtra("url", msg.getContent());
                startActivity(intent);
                break;
            case Const.MSG_TYPE_VOICE://语音

                break;
            case Const.MSG_TYPE_MUSIC://音乐
                String[] musicinfo = msg.getContent().split(Const.SPILT);
                if (musicinfo.length == 3) {//音乐链接，歌曲名，作者
                    if (TextUtils.isEmpty(msg.getBak1()) || msg.getBak1().equals("0")) {
                        stopOldMusic();
                        msg.setBak1("1");
                        listMsg.remove(position);
                        listMsg.add(position, msg);
                        mAdapter.notifyDataSetChanged();
                        playMusic(musicinfo);
                    } else {
                        if (musicPlayManager != null) {
                            ll_playing.setVisibility(View.GONE);
                            musicPlayManager.stop();
                        }
                        msg.setBak1("0");
                        listMsg.remove(position);
                        listMsg.add(position, msg);
                        mAdapter.notifyDataSetChanged();
                    }

                }
                break;
        }
    }

    @Override
    public void longClick(int position) {//长按
        Msg msg = listMsg.get(position);
        switch (msg.getType()) {
            case Const.MSG_TYPE_TEXT://文本
                clip(msg, position);
                break;
            case Const.MSG_TYPE_IMG://图片
                break;
            case Const.MSG_TYPE_LOCATION://位置
            case Const.MSG_TYPE_MUSIC://音乐
            case Const.MSG_TYPE_VOICE://语音
            case Const.MSG_TYPE_LIST://列表
                delonly(msg, position);
                break;
        }
    }

    /**
     * 播放网络音乐
     *
     * @param musicinfo
     */
    void playMusic(final String[] musicinfo) {
        ll_playing.setVisibility(View.VISIBLE);
        tv_playing.setText("正在播放歌曲：《" + musicinfo[1] + "》—" + musicinfo[2]);
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    musicPlayManager.play(musicinfo[0]);
                } catch (Exception e) {
                    e.printStackTrace();
                    LogUtil.e("音乐播放异常>>" + e.getMessage());
                    stopOldMusic();
                    Looper.prepare();
                    ToastUtil.showToast(ChatPullRefListActivity.this, "播放错误，请重试");
                    Looper.loop();
                }
            }
        }).start();
    }

    /**
     * 停止之前正在播放的音乐
     */
    void stopOldMusic() {
        for (int i = 0; i < listMsg.size(); i++) {
            Msg msg = listMsg.get(i);
            if (!TextUtils.isEmpty(msg.getBak1()) && msg.getBak1().equals("1")) {
                msg.setBak1("0");
                listMsg.remove(i);
                listMsg.add(i, msg);
                mAdapter.notifyDataSetChanged();
                if (musicPlayManager != null) {
                    ll_playing.setVisibility(View.GONE);
                    musicPlayManager.stop();
                }
                break;
            }
        }
    }

    /**
     * 带复制文本的操作
     */
    void clip(final Msg msg, final int position) {
        new ActionSheetBottomDialog(this)
                .builder()
                .addSheetItem("复制", ActionSheetBottomDialog.SheetItemColor.Blue, new ActionSheetBottomDialog.OnSheetItemClickListener() {
                    @Override
                    public void onClick(int which) {
                        ClipboardManager cmb = (ClipboardManager) ChatPullRefListActivity.this.getSystemService(ChatActivity.CLIPBOARD_SERVICE);
                        cmb.setText(msg.getContent());
                        ToastUtil.showToast(ChatPullRefListActivity.this, "已复制到剪切板");
                    }
                })
                .addSheetItem("朗读", ActionSheetBottomDialog.SheetItemColor.Blue, new ActionSheetBottomDialog.OnSheetItemClickListener() {
                    @Override
                    public void onClick(int which) {
//                        speechSynthesizerUtil.speech(msg.getContent());
                    }
                })
                .addSheetItem("删除", ActionSheetBottomDialog.SheetItemColor.Blue, new ActionSheetBottomDialog.OnSheetItemClickListener() {
                    @Override
                    public void onClick(int which) {
                        listMsg.remove(position);
                        offset = listMsg.size();
                        mAdapter.notifyDataSetChanged();
                        msgDao.deleteMsgById(msg.getMsgId());
                    }
                })
                .show();
    }

    /**
     * 仅有删除操作
     */
    void delonly(final Msg msg, final int position) {
        new ActionSheetBottomDialog(this)
                .builder()
                .addSheetItem("删除", ActionSheetBottomDialog.SheetItemColor.Blue, new ActionSheetBottomDialog.OnSheetItemClickListener() {
                    @Override
                    public void onClick(int which) {
                        listMsg.remove(position);
                        offset = listMsg.size();
                        mAdapter.notifyDataSetChanged();
                        msgDao.deleteMsgById(msg.getMsgId());
                        if (msg.getType()==Const.MSG_TYPE_MUSIC) {
                            if (musicPlayManager != null) {
                                ll_playing.setVisibility(View.GONE);
                                musicPlayManager.stop();
                            }
                        }
                    }
                })
                .show();
    }

//    /**
//     * 录音完毕
//     * text 录音转文字后的内容
//     */
//    @Override
//    public void recoComplete(String text) {
//        String voicepath = Const.FILE_VOICE_CACHE + System.currentTimeMillis() + ".wav";
//        if (SysUtils.copyFile(Const.FILE_VOICE_CACHE + "iat.wav", voicepath)) {
//            sendMsgVoice(voicepath + Const.SPILT + text);
//        } else {
//            ToastUtil.showToast(this, "录音失败");
//        }
//    }

    /**
     * 表情页改变时，dots效果也要跟着改变
     */
    class PageChange implements OnPageChangeListener {
        @Override
        public void onPageScrollStateChanged(int arg0) {
        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {
        }

        @Override
        public void onPageSelected(int arg0) {
            for (int i = 0; i < mDotsLayout.getChildCount(); i++) {
                mDotsLayout.getChildAt(i).setSelected(false);
            }
            mDotsLayout.getChildAt(arg0).setSelected(true);
        }
    }

    /**
     * 下拉加载更多
     */
    int addPage = 1;
    @Override
    public void onRefresh() {
//        List<Msg> list = msgDao.queryMsg(from, to, offset);
//        if (list.size() <= 0) {
//            mListView.setSelection(0);
//            mListView.onRefreshCompleteHeader();
//            return;
//        }
//        listMsg.addAll(0, list);
//        offset = listMsg.size();
//        mListView.onRefreshCompleteHeader();
//        mAdapter.notifyDataSetChanged();
//        mListView.setSelection(list.size());
        
		if(addPage == pageCount-1){
			mListView.setSelection(0);
            mListView.onRefreshCompleteHeader();
			return;
		}
		else if(addPage < pageCount-1){
		    ++addPage;	
		}
        try{
        	if (mChat != null)
			    temp1 = mChat.getMessagesByPageIndex(pageSize, addPage);//HISTORY_MAX_SIZE 1    
        	else{
//        		AccountUser = sharedPrefs.getString("uidStr", "")+"@0";
//            	Participant = mContact.getJID();
            	temp1 = chatAdapterOffline.getMessagesByPageIndex(AccountUser, Participant,pageSize, addPage);//HISTORY_MAX_SIZE 1  
        	}
        		
			if(temp1!=null && temp1.size()!=0){
			    msgList = convertMessagesList(temp1);
			    duitangs2.addAll(msgList);
			    temp1 = null;
			    msgList = null;
	//		    onLoadMore();
//			    mAdapter.removeAll();//清除掉所有记录
			    
//			    onAddMessage();
			    mAdapter.addItemTop(duitangs2);
                mAdapter.notifyDataSetChanged();
//                mListView.setSelection(mAdapter.getCount()-1);
                mListView.setSelection(duitangs2.size()-1);
                duitangs2.clear();
			    
			    mListView.onRefreshCompleteHeader();
			}else{
				mListView.setSelection(0);
	            mListView.onRefreshCompleteHeader();
			}
        }catch(RemoteException e){
        	e.printStackTrace();
        	mListView.setSelection(0);
            mListView.onRefreshCompleteHeader();
        }catch(Exception e){
        	e.printStackTrace();
        	mListView.setSelection(0);
            mListView.onRefreshCompleteHeader();
        }
        
    }


    @Override
    protected void onResume() {
        super.onResume();
		if (!mBinded){
		    mBinded = getApplicationContext().bindService(SERVICE_INTENT, mServConn, BIND_AUTO_CREATE);
		    mBinded = true;	
		}
//		if (mBinded){
//	        Intent intent = getIntent(); 
//	        //0普通图片listview 1瀑布流  2地图模式
//	        uListype = intent.getIntExtra("uListypefor", (int) 0);  
//	        Log.e("================20130804uListype resume1================", "++++++++++++++ContactlistWithPop uListype="+uListype);
//	        mImageFetcher.setUListype(uListype);
//	        mImageFetcher.setExitTasksEarly(false);
//		}
		if(mContact!=null){//群聊
			try{
			    mChat = mChatManager.getChat(mContact);
				if (mChat == null) {
		//			if(mChatManager!=null)
				    mChat = mChatManager.createChat(mContact, null);//mMessageListener
		//			if(mChat!=null)
				    mChat.setOpen(true);
				    Log.e("※※※※※20170810(333)※※※※※", "mChat.setOpen(true)");
				    mChatManager.deleteChatNotification(mChat);//删除notification
				    
				}
				mChat.setOpen(true);
				Log.e("※※※※※20170810(444)※※※※※", "mChat.setOpen(true)");
				mChatManager.deleteChatNotification(mChat);//删除notification
			}catch(Exception e){}
		}
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                //让输入框获取焦点
                input.requestFocus();
                if (chat_face_container.getVisibility() == View.VISIBLE || chat_add_container.getVisibility() == View.VISIBLE) {
                    hideSoftInputView();
                }
            }
        }, 100);

    }

    /**
     * 监听返回键
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
        	if((chat_face_container.getVisibility() == View.GONE)
        			&& (chat_add_container.getVisibility() == View.GONE)
        			&& (musicPlayManager == null || !musicPlayManager.isPlaying())){
        		if(event.getRepeatCount() == 0){
        			Log.d("================20170507 ChatActivity onBackPressed================", "+++++++onBackPressed+++++++jid="+jid);
        			//通知ContactListPullRefListActivity更新局部 消息图章为0，不显示消息图章
        			Intent i = new Intent(ChatPullRefListActivity.this,ContactFrameActivity.class);//ContactListPullRefListActivity
        			i.putExtra("jid",jid);
        			i.putExtra("contactuserid",jid);
        			i.putExtra("refreshlistviewonerow","1");
        			startActivity(i);
        			finish();
        		}
        		
        	}else{
            hideSoftInputView();
            if (chat_face_container.getVisibility() == View.VISIBLE) {
                chat_face_container.setVisibility(View.GONE);
            } else if (chat_add_container.getVisibility() == View.VISIBLE) {
                chat_add_container.setVisibility(View.GONE);
            } else {
                if (musicPlayManager != null && musicPlayManager.isPlaying()) {
                    musicPlayManager.stop();
                }
//                if (speechSynthesizerUtil != null) {
//                    speechSynthesizerUtil.stopSpeech();
//                }
                finish();
            }
        	}
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
    /**
     * 获取录音时动画效果的图片
     */
    public static Drawable[] getRecordAnimPic(Resources res) {
        return new Drawable[]{res.getDrawable(R.drawable.amp1),
                res.getDrawable(R.drawable.amp2), res.getDrawable(R.drawable.amp3),
                res.getDrawable(R.drawable.amp4), res.getDrawable(R.drawable.amp5),
                res.getDrawable(R.drawable.amp6), res.getDrawable(R.drawable.amp7)};
    }
	  @Override
	  public void finish() {
	      super.finish();
	      
	      overridePendingTransition(R.anim.push_in_left, R.anim.push_out_right);
	      onDestroy();
	  }
    @Override
    protected void onDestroy() {
    	Log.e("※※※※※ChatActivity onDestroy start※※※※※", "※※ChatActivity onDestroy start※※");
		super.onDestroy();
		
		
// 	    XmppConnectionAdapter.isPause = true;
////		if(XmppConnectionAdapter.instance!=null)
////			XmppConnectionAdapter.instance.resetApplication();
//		XmppConnectionAdapter.instance = null;
//		stopService(SERVICE_INTENT);
//		loadingView.isStop = true;
	    try{
		    if (mChat != null) {
				mChat.setOpen(false);
				Log.e("※※※※※20170810(555)※※※※※", "mChat.setOpen(false)");
				mChat.removeMessageListener(mMessageListener);
//				mChat = null;
			}
		    if (mChatManager != null){
//		    	mChatManager.destroyChat(mChat);//删除掉20170810
		    	Log.e("※※※※※20170810(555555)※※※※※", "destroyChat(mChat)");
//		    	mChatManager.ReloadChatListener();
				mChatManager.removeChatCreationListener(mChatManagerListener);
//				mChatManager = null;
		    }
		    if(mXmppFacade!=null && mXmppFacade.getXmppConnectionAdapter()!=null)
		    	mXmppFacade.getXmppConnectionAdapter().unRegisterConnectionStatusCallback();
	    }catch (RemoteException e) {
	    	e.printStackTrace();
	    }catch (Exception e){
	    	e.printStackTrace();
	    }
		if (mBinded) {
			getApplicationContext().unbindService(mServConn);
		    mBinded = false;
		}
        mChat = null;
        mChatManager = null;
		mXmppFacade = null;
		
//		this.unregisterReceiver(mNetWorkReceiver); // 删除广播
		if(tm!=null){
			tm.listen(myPhoneCallListener,PhoneStateListener.LISTEN_NONE);//取消监听即可
			tm = null;
		}
		if(myPhoneCallListener!=null)
			myPhoneCallListener = null;
		
		mAdapter =  null;
//		upload = false;
		if(duitangs2!=null){
			duitangs2.clear();
			duitangs2=null;
		}
		clearAsyncTask();
    }
    
    
    
//	private View mNetErrorView;
//	private TextView mConnect_status_info;
//	private ImageView mConnect_status_btn;
    private exPhoneCallListener myPhoneCallListener = null;
    private TelephonyManager tm = null;
    
    private static final Intent SERVICE_INTENT = new Intent();
	static {
		//pkg,cls
//		SERVICE_INTENT.setComponent(new ComponentName("com.test", "com.stb.isharemessage.BeemService"));
//		SERVICE_INTENT.setComponent(new ComponentName("com.stb.isharemessage", "com.stb.isharemessage.BeemService"));
		SERVICE_INTENT.setComponent(new ComponentName("com.spice.im", "com.stb.isharemessage.BeemService"));//自身应用pkg名称，非service所在pkg名称
	}
	private final ServiceConnection mServConn = new BeemServiceConnection();
    private boolean mBinded = false;
    private IXmppFacade mXmppFacade;

    
	private void sendMsgIQ() {

		putAsyncTask(new AsyncTask<Void, Void, Boolean>() {

			@Override
			protected void onPreExecute() {
				super.onPreExecute();
//				showLoadingDialog("正在加载,请稍后...");
			}

			@Override
			protected Boolean doInBackground(Void... params) {
				sendMsgIQ_fuc();
				return true;
			}

			@Override
			protected void onPostExecute(Boolean result) {
				super.onPostExecute(result);
//				dismissLoadingDialog();
				if (!result) {
//					showCustomToast("数据加载失败...");
//					mHandler2.sendEmptyMessage(3);
				} else {
//					mHandler2.sendEmptyMessage(0);
				}
			}

		});
	}
    
	private String[] errorMsg = new String[]{"抱歉,没有找到相关结果.",
			"服务连接中1-1,请稍候再试.",
			"服务连接中1-2,请稍候再试.",
			"服务连接中1-3,请稍候再试.",
			"网络连接不可用,请检查你的网络设置.",
			"",
			"请求异常,稍候重试!"};
	private int errorType = 5;
    boolean sendMsgIQ_fuc(){
		if(BeemConnectivity.isConnected( getApplicationContext())){
			Log.e("================2015 TestActivity.java ================", "++++++++++++++initContactList()222++++++++++++++");
		    try {
		    	if(mXmppFacade!=null){
		    		Log.e("================2015 TestActivity.java ================", "++++++++++++++initContactList()333++++++++++++++");
			    	if (mXmppFacade.getXmppConnectionAdapter()!=null 
							&& mXmppFacade.getXmppConnectionAdapter().getAdaptee()!=null
							&& mXmppFacade.getXmppConnectionAdapter().getAdaptee().isConnected() 
			    			&& mXmppFacade.getXmppConnectionAdapter().getAdaptee().isAuthenticated()
			    			&& mXmppFacade.getXmppConnectionAdapter().getAdaptee().isAlive()
			    			){
			    		
			    		MsgIQ reqXML = new MsgIQ();
			            reqXML.setId("1234567890");
			            reqXML.setApikey("abcdefghijklmnopqrstuvwxyz");
			            reqXML.setMsgType1(0);
			            reqXML.setMsgType2(0);
			            String partnerid = mXmppFacade.getXmppConnectionAdapter().getMService().getPartnerid();
			            reqXML.setPartnerid(partnerid);
			            SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
					    String login = settings.getString(BeemApplication.ACCOUNT_USERNAME_KEY, "");
			            String uuid = mXmppFacade.getXmppConnectionAdapter().getAdaptee().getUUID(this,login);
			            reqXML.setFromUserUuid(uuid);
			            reqXML.setToUserUuid(uuid);
//			            String hashcode = "";//partnerid+touserUuid+fromUserUuid 使用登录成功后返回的sessionid作为密码做3des运算
			            String hash_dest_src = partnerid+ uuid+uuid;
			            String hash_dest = EncryptionUtil.getHash2(hash_dest_src, "SHA");
			            reqXML.setHash(hash_dest);
			            reqXML.setType(IQ.Type.SET);
			            String elementName = "msgiq"; 
			    		String namespace = "com:isharemessage:msgiq";
			    		ContactGroupListIQResponseProvider provider = new ContactGroupListIQResponseProvider();
//			            Packet rt =  mXmppFacade.getXmppConnectionAdapter().excute(reqXML, "msgiq", "com:isharemessage:msgiq", provider);
//			            String retcode = "";
//			            if(rt!=null){
//			                if (rt instanceof MsgIQResponse) {
//			                	final MsgIQResponse msgIQResponse = (MsgIQResponse) rt;
//
//			                    if (msgIQResponse.getChildElementXML().contains(
//			                            "com:isharemessage:msgiq")) {
////			    					ChatActivity.this.runOnUiThread(new Runnable() {
////				                    	
////            							@Override
////            							public void run() {
////            								showCustomToast("服务器应答消息："+contactGroupListIQResponse.toXML().toString());
////            							}
////            						});
//			                        retcode = msgIQResponse.getRetcode();
//			                        
//			                    }
//			                } 
//			            }
//			            
//			    		Log.e("================2015 TestActivity.java ================", "++++++++++++++initContactList()444++++++++++++++");
//
//			    	    if(retcode!=null && retcode.equalsIgnoreCase("0000")){
//			    	    	errorType = 5;
//			    	    	return true;
//			    	    }else{
//			    	    	if(retcode!=null && !retcode.equalsIgnoreCase("0000"))
//			    	    		errorType = 0;
//			    	    	else
//			    	    		errorType = 6;
//			    	    }
			    		mXmppFacade.getXmppConnectionAdapter().getAdaptee().sendPacket(reqXML);//异步方式
						mBinded = true;//20130804 added by allen
			    	}else
			    		errorType = 1;
		    	}else
		    		errorType = 2;
				
		    } catch (RemoteException e) {
		    	errorType = 3;
		    	e.printStackTrace();
		    	
		    } catch (Exception e){
		    	errorType = 3;
		    	e.printStackTrace();
		    }
	    }else{
	    	errorType = 4;
	    }
		return false;
    }
    
    boolean sendMsgIQ_fuc2(String sendStr){
    	if (!"".equals(sendStr)) {
		    com.stb.core.chat.Message msgToSend = new com.stb.core.chat.Message(StringUtils.parseBareAddress(mContact.getJID()), com.stb.core.chat.Message.MSG_TYPE_CHAT);
		    msgToSend.setMbody(sendStr);
		    msgToSend.setMisoffline(1);
		    if(mContact.getJID().indexOf("@1")!=-1)//群组消息的话，mfrom为 "群组的tagid@1/用户的uid，即 tagid@1/uid"
		    	msgToSend.setMfrom(StringUtils.parseBareAddress(mContact.getJID())+"/"+StringUtils.parseBareAddress2(myjid));
		    else
		    	msgToSend.setMfrom(myjid);
		    int id = 0;
		    boolean except = false;
		    try {
//			    	mChat = mChatManager.getChat(mContact);
				if (mChat == null) {
				    mChat = mChatManager.createChat(mContact, mMessageListener);
				    mChat.setOpen(true);
				    Log.e("※※※※※20170810(666)※※※※※", "mChat.setOpen(true)");
				}
//				mChat.setOpen(true);
//				mChat.getAccountUser();
				id = mChat.sendMessage(msgToSend);
		    } catch (RemoteException e) {
		    	except = true;
				Log.e(TAG, e.getMessage());
				XmppConnectionAdapter.saveAsOfflineMessage(getContentResolver(), mContact.getJID(), sendStr);//待自动重发的消息
				msgToSend.setMisoffline(2);//mIsOffline 0 other发送中,1 false notoffline发送成功, 2true 发送失败isoffline
				chatAdapterOffline.addMessage(AccountUser, Participant, msgToSend);//如果断开了连接（无论是服务器宕机还是客户端本身问题）记录到本地sqlite中存储的聊天记录，供聊天窗口展示
		    
		    } 
		    /*
		    catch(IllegalStateException e){//20200316 增加
				Log.e(TAG, e.getMessage());
				XmppConnectionAdapter.saveAsOfflineMessage(getContentResolver(), mContact.getJID(), sendStr);
		    } */
		    catch(Exception e){//20200316 增加
		    	except = true;
				Log.e(TAG, e.getMessage());
				XmppConnectionAdapter.saveAsOfflineMessage(getContentResolver(), mContact.getJID(), sendStr);
				msgToSend.setMisoffline(2);//mIsOffline 0 other发送中,1 false notoffline发送成功, 2true 发送失败isoffline
				chatAdapterOffline.addMessage(AccountUser, Participant, msgToSend);//如果断开了连接（无论是服务器宕机还是客户端本身问题）记录到本地sqlite中存储的聊天记录，供聊天窗口展示
		    
		    }
		    
		    final String self = getString(R.string.chat_self);

//		    MessageText temp = new MessageText(com.spice.im.chat.MessageText.MESSAGE_TYPE.SEND,self, self, sendStr, false, new Date());
		    MessageText temp = null;
//		    if(mContact.getJID().indexOf("@1")!=-1)//群组消息的话，mfrom为 "群组的tagid@1/用户的uid，即 tagid@1/uid"
		    	temp = new MessageText(com.spice.im.chat.MessageText.MESSAGE_TYPE.SEND,msgToSend.getMfrom(), self, sendStr, false, new Date());
		    
		    	
		    temp.setId(id);
		    if(except)
		    	temp.setIsOffline(2);
		    else
		    	temp.setIsOffline(1);
		    
		    duitangs2.add(temp);

		    onAddMessage();
		    return true;
    	}
    	return false;
    }
    
	@Override
	public void connectionStatusChanged(int connectedState, String reason) {
		Log.e("MMMMM20140604MMMMMMMMMMMM", "++++++++++++++connectionStatusChanged0++++++++++++");
		switch (connectedState) {
		case 0://connectionClosed
			mHandler3.sendEmptyMessage(0);
			break;
		case 1://connectionClosedOnError
//			mConnectErrorView.setVisibility(View.VISIBLE);
//			mNetErrorView.setVisibility(View.VISIBLE);
//			mConnect_status_info.setText("连接异常!");
			mHandler3.sendEmptyMessage(1);
			break;
		case 2://reconnectingIn
//			mNetErrorView.setVisibility(View.VISIBLE);
//			mConnect_status_info.setText("连接中...");
			mHandler3.sendEmptyMessage(2);
			break;
		case 3://reconnectionFailed
//			mNetErrorView.setVisibility(View.VISIBLE);
//			mConnect_status_info.setText("重连失败!");
			mHandler3.sendEmptyMessage(3);
			break;
		case 4://reconnectionSuccessful
//			mNetErrorView.setVisibility(View.GONE);
			mHandler3.sendEmptyMessage(4);

		default:
			break;
		}
	}
	Handler mHandler3 = new Handler() {

		@Override
		public void handleMessage(android.os.Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case 0:
				break;

			case 1:
				mNetErrorView.setVisibility(View.VISIBLE);
				if(BeemConnectivity.isConnected(mContext))
				mConnect_status_info.setText("连接异常!");
				break;

			case 2:
				mNetErrorView.setVisibility(View.VISIBLE);
				if(BeemConnectivity.isConnected(mContext))
				mConnect_status_info.setText("连接中...");
				break;
			case 3:
				mNetErrorView.setVisibility(View.VISIBLE);
				if(BeemConnectivity.isConnected(mContext))
				mConnect_status_info.setText("重连失败!");
				break;
				
			case 4:
				mNetErrorView.setVisibility(View.GONE);
				String udid = "";
				String partnerid = "";
				try{
					udid = mXmppFacade.getXmppConnectionAdapter().getAdaptee().UDID;
					partnerid = mXmppFacade.getXmppConnectionAdapter().getMService().getPartnerid();
				}catch(Exception e){
					e.printStackTrace();
				}
				break;
			case 5:
				mNetErrorView.setVisibility(View.VISIBLE);
				mConnect_status_info.setText("当前网络不可用，请检查你的网络设置。");
				break;
			case 6:
				if(mXmppFacade!=null 
//						&& mXmppFacade.getXmppConnectionAdapter()!=null 
//						&& mXmppFacade.getXmppConnectionAdapter().getAdaptee()!=null//&& !mXmppFacade.getXmppConnectionAdapter().getAdaptee().isAuthenticated()
//						&& mXmppFacade.getXmppConnectionAdapter().getAdaptee().isConnected()
//						&& mXmppFacade.getXmppConnectionAdapter().getAdaptee().isAuthenticated()
						&& BeemConnectivity.isConnected(mContext)){
					
				}else{
					mNetErrorView.setVisibility(View.VISIBLE);
					if(BeemConnectivity.isConnected(mContext))
					mConnect_status_info.setText("网络可用,连接中...");
				}
				break;	
			}
		}

	};
	private BroadcastReceiver mNetWorkReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();  
            if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {  
                Log.d("PoupWindowContactList", "网络状态已经改变");  
//                connectivityManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);  
//                info = connectivityManager.getActiveNetworkInfo();    
//                if(info != null && info.isAvailable()) {  
//                    String name = info.getTypeName();  
//                    Log.d(tag, "当前网络名称：" + name);  
//                    //doSomething()  
//                } else {  
//                    Log.d(tag, "没有可用网络");  
//                  //doSomething()  
//                }  
                if(BeemConnectivity.isConnected(context)){
//                	mNetErrorView.setVisibility(View.GONE);
//                	isconnect = 0;
                	mHandler3.sendEmptyMessage(6);//4
                }else{
//                	mNetErrorView.setVisibility(View.VISIBLE);
//                	isconnect = 1;
                	mHandler3.sendEmptyMessage(5);
                	Log.d("PoupWindowContactList", "当前网络不可用，请检查你的网络设置。");
                }
            } 
        }
	};
	
	private boolean phonestate = false;//false其他， true接起电话或电话进行时 
    /* 内部class继承PhoneStateListener */
    public class exPhoneCallListener extends PhoneStateListener
    {
        /* 重写onCallStateChanged
        当状态改变时改变myTextView1的文字及颜色 */
        public void onCallStateChanged(int state, String incomingNumber)
        {
          switch (state)
          {
            /* 无任何状态时 :说明没有拨打电话的界面的时候，也就是在拨打电话前和挂电话后的情况*/
            case TelephonyManager.CALL_STATE_IDLE:
            	Log.e("================20131216 无任何电话状态时================", "无任何电话状态时");
            	if(phonestate){
            		onPhoneStateResume();
            	}
            	phonestate = false;
              break;
            /* 接起电话时 :至少有一个电话存在、拨出或激活、接听，而没有一个电话在通话或等待的状态*/
            case TelephonyManager.CALL_STATE_OFFHOOK:
            	Log.e("================20131216 接起电话时================", "接起电话时");
            	onPhoneStatePause();
            	phonestate = true;
              break;
            /* 电话进来时 :在通话的过程中*/
            case TelephonyManager.CALL_STATE_RINGING:
//              getContactPeople(incomingNumber);
            	Log.e("================20131216 电话进来时================", "电话进来时");
//            	onBackPressed();
            	onPhoneStatePause();
            	phonestate = true;
              break;
            default:
              break;
          }
          super.onCallStateChanged(state, incomingNumber);
        }
    }
    
    protected void onPhoneStatePause() {
//		super.onPause();
    	try{

		if (mBinded) {
			getApplicationContext().unbindService(mServConn);
		    mBinded = false;
		}
		mXmppFacade = null;
    	}catch(Exception e){
    		e.printStackTrace();
    	}
    }
    
    protected void onPhoneStateResume() {
//		super.onResume();
    	try{
		if (!mBinded){
//		    new Thread()
//		    {
//		        @Override
//		        public void run()
//		        {
		    mBinded = getApplicationContext().bindService(SERVICE_INTENT, mServConn, BIND_AUTO_CREATE);

//		        }
//		    }.start();		    
		}
		if (mBinded){
//			mImageFetcher.setExitTasksEarly(false);
		}
    	}catch(Exception e){
    		e.printStackTrace();
    	}
    }
    
    /*
     * 打开设置网络界面
     * */
    public static void setNetworkMethod(final Context context){
        //提示对话框
        AlertDialog.Builder builder=new AlertDialog.Builder(context);
        builder.setTitle("网络设置提示").setMessage("网络连接不可用,是否进行设置?").setPositiveButton("设置", new DialogInterface.OnClickListener() {
            
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub
                Intent intent=null;
                //判断手机系统的版本  即API大于10 就是3.0或以上版本 
                if(android.os.Build.VERSION.SDK_INT>10){
                    intent = new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS);
                }else{
                    intent = new Intent();
                    ComponentName component = new ComponentName("com.android.settings","com.android.settings.WirelessSettings");
                    intent.setComponent(component);
                    intent.setAction("android.intent.action.VIEW");
                }
                context.startActivity(intent);
            }
        }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
            
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub
                dialog.dismiss();
            }
        }).show();
    }
    
    
    
	protected FlippingLoadingDialog mLoadingDialog;
	protected void showLoadingDialog(String text) {
		if (text != null) {
			mLoadingDialog.setText(text);
		}
		mLoadingDialog.show();
	}

	protected void dismissLoadingDialog() {
		if (mLoadingDialog.isShowing()) {
			mLoadingDialog.dismiss();
		}
	}
	/** 显示自定义Toast提示(来自String) **/
	protected void showCustomToast(String text) {
		View toastRoot = LayoutInflater.from(ChatPullRefListActivity.this).inflate(
				R.layout.common_toast, null);
		((HandyTextView) toastRoot.findViewById(R.id.toast_text)).setText(text);
		Toast toast = new Toast(ChatPullRefListActivity.this);
		toast.setGravity(Gravity.CENTER, 0, 0);
		toast.setDuration(Toast.LENGTH_SHORT);
		toast.setView(toastRoot);
		toast.show();
	}
    private DuitangInfoAdapter duitangInfoAdapter = null;//用户信息存入本地数据库
    private void getChatPullRefList() {

		putAsyncTask(new AsyncTask<Void, Void, Boolean>() {

			@Override
			protected void onPreExecute() {
				super.onPreExecute();
				showLoadingDialog("正在加载,请稍后...");
			}

			@Override
			protected Boolean doInBackground(Void... params) {
				return initChatPullRefList();
//				return true;
			}

			@Override
			protected void onPostExecute(Boolean result) {
				super.onPostExecute(result);
				dismissLoadingDialog();
				if (!result) {
					showCustomToast("数据加载失败...");
				} else {
					mHandler.sendEmptyMessage(1);
				}
			}

		});
	}
	public boolean initChatPullRefList(){
		boolean bolRes = false;
	    try {
	//		mRoster = mXmppFacade.getRoster();
	////    	mRoster = mXmppFacade.getRosterWithIndexNumber(0,653333333);
	//		xmppConnectionAdapter = (XmppConnectionAdapter)mXmppFacade.createConnection();//获取当前连接
	////		xmppConnectionAdapter = mXmppFacade.getXmppConnectionAdapter();
	//		if (mRoster != null)
	//		    mRoster.addRosterListener(mBeemRosterListener);
	    	
//			mChatManager = mXmppFacade.getChatManager();
			
			if (mChatManager != null) {
			    mChatManager.addChatCreationListener(mChatManagerListener);
			    changeCurrentChat();
			} else {
				preLoadplayRegisteredTranscript();//20200317 增加 如果断开了连接（无论是服务器宕机还是客户端本身问题）第一次进入Chat聊天界面初始化时，查询本地sqlite中存储的聊天记录
			}
			
			
			
			if(mContact!=null ){//去掉&& mChatManager != null，适应 断开了连接 的情况
				UnReadMsgNumber unReadMsgNumber = new UnReadMsgNumber();
			    unReadMsgNumber.setKey(StringUtils.parseBareAddress(mContact.getJID()));
			    unReadMsgNumber.setUnreadnumber(0);
			    duitangInfoAdapter.addUnReadMsgNumber(unReadMsgNumber);
			    
			}
			bolRes = true;
	    } catch (RemoteException e) {
			Log.e(TAG, e.getMessage());
			bolRes = false;
	    } catch(Exception e){
	    	Log.e(TAG, e.getMessage());
	    	bolRes = false;
	    }
	    
	    return bolRes;
	}
    
    
    private IChat mChat;
    private IChatManager mChatManager;
    private final IChatManagerListener mChatManagerListener = new ChatManagerListener();
    private String myjid = "";
    /**
     * The service connection used to connect to the Beem service.
     */
    private class BeemServiceConnection implements ServiceConnection {
		/**
		 * Constructor.
		 */
		public BeemServiceConnection() {
		}
	
		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
		    mXmppFacade = IXmppFacade.Stub.asInterface(service);
		    if(mXmppFacade!=null){
		    	mBinded = true;
		    	try{
		    		mXmppFacade.getXmppConnectionAdapter().registerConnectionStatusCallback(ChatPullRefListActivity.this);
		    		mChatManager = mXmppFacade.getChatManager();
//		    		mChat = mChatManager.getChat(mContact);
		    		myjid = mXmppFacade.getXmppConnectionAdapter().getJID();
		    	}catch(Exception e){
		    		e.printStackTrace();
		    	}
//		    	getContactList();
//		    	getData(0);
//		    	getContactList(0);
		    	getChatPullRefList();
		    }
		}
		@Override
		public void onServiceDisconnected(ComponentName name) {
//			if(mRoster!=null)
//			    try {
//			    	mRoster.removeRosterListener(mBeemRosterListener);
//			    } catch (RemoteException e) {
//				e.printStackTrace();
//			    }
		    try{
			    if(mXmppFacade!=null && mXmppFacade.getXmppConnectionAdapter()!=null)
			    	mXmppFacade.getXmppConnectionAdapter().unRegisterConnectionStatusCallback();
		    }catch (RemoteException e) {
		    	e.printStackTrace();
		    }catch(Exception e){
		    	e.printStackTrace();
		    }
		    if(mChatManager!=null)
		    	try{
		    	mChatManager.removeChatCreationListener(mChatManagerListener);
		    	}catch(RemoteException e){
		    		e.printStackTrace();
		    	}catch(Exception e){
		    		e.printStackTrace();
		    	}
		    if (mChat != null) {
		    	try{
				mChat.setOpen(false);
				Log.e("※※※※※20170810(777)※※※※※", "mChat.setOpen(false)");
				mChat.removeMessageListener(mMessageListener);
		    	}catch(RemoteException e){
		    		e.printStackTrace();
		    	}catch(Exception e){
		    		e.printStackTrace();
		    	}
			}
		    mXmppFacade = null;
		    mChatManager = null;
//		    mRoster = null;
		    mBinded = false;
		}
    }
    
    private class ChatManagerListener extends IChatManagerListener.Stub {

		/**
		 * Constructor.
		 */
		public ChatManagerListener() {
		}
	
		@Override
		public void chatCreated(IChat chat, boolean locally) {
			Log.e("※※※※※20170810(888888)※※※※※", "chatCreated(IChat chat, boolean locally) locally="+locally+";mContact.getJID()="+mContact.getJID());
		    if (locally)
			return;
		    try {
		    	Log.e("※※※※※20170810(999999)※※※※※", "chatCreated(IChat chat, boolean locally) locally="+locally+";mContact.getJID()="+mContact.getJID()+";chat.getParticipant().getJID()="+chat.getParticipant().getJID());
//			    chat.addMessageListener(mMessageListener);
		    	
//			    mChatManager.deleteChatNotification(mChat);
				String contactJid = StringUtils.parseBareAddress(mContact.getJID());
				String chatJid = StringUtils.parseBareAddress(chat.getParticipant().getJID());
				if (chatJid.equals(contactJid)) {
				    // This should not be happened but to be sure
				    if (mChat != null) {
					mChat.setOpen(false);
					Log.e("※※※※※20170810(888)※※※※※", "mChat.setOpen(false)");
					mChat.removeMessageListener(mMessageListener);
				    }
				    mChat = chat;
				    mChat.setOpen(true);
				    Log.e("※※※※※20170810(999)※※※※※", "mChat.setOpen(true)");
				    mChat.addMessageListener(mMessageListener);
				    mChatManager.deleteChatNotification(mChat);
				}
		    } catch (RemoteException ex) {
			Log.e("MainListActivity", "A remote exception occurs during the creation of a chat", ex);
		    }catch(Exception e){
		    	e.printStackTrace();
		    }
		}
    } 
    
	private final IMessageListener mMessageListener = new OnMessageListener();
    private class OnMessageListener extends IMessageListener.Stub {
    	
		/**
		 * Constructor.
		 */
		public OnMessageListener() {
		}
	
		/**
		 * {@inheritDoc}.
		 * handle the received messages and refresh the chat message list UI
		 */
		@Override
		public void processMessage(IChat chat, final com.stb.core.chat.Message msg) throws RemoteException {
//		    final String fromBareJid = StringUtils.parseBareAddress(msg.getMfrom());
			final String fromBareJid = msg.getMfrom();
		    Log.e("※※※※※####20141023ContactListPullRefListActivity2####※※※※※", "※※ChatListener processMessage※※:from="+msg.getMfrom()+";body="+msg.getMbody());
			mHandler.post(new Runnable() {
				
			    @Override
			    public void run() {
				if (msg.getMtype() == com.stb.core.chat.Message.MSG_TYPE_ERROR) {
//				    mListMessages.add(new MessageText(fromBareJid, mContact.getName(), msg.getBody(), true, msg
//					.getTimestamp()));
//				    mAdapter.notifyDataSetChanged();
//					duitangs2.clear();
				    duitangs2.add(new MessageText(com.spice.im.chat.MessageText.MESSAGE_TYPE.RECEIVER,fromBareJid, mContact.getName()!=null?mContact.getName():"", msg.getMbody(), true, msg
							.getMtimestamp()));

//				    onLoadMore();
				    onAddMessage();

				} else if (msg.getMbody() != null) {
//					mListMessages.add(new MessageText(fromBareJid, mContact.getName(), msg.getBody(),
//					    false, msg.getTimestamp()));
//				    mAdapter.notifyDataSetChanged();
//					duitangs2.clear();
				    duitangs2.add(new MessageText(com.spice.im.chat.MessageText.MESSAGE_TYPE.RECEIVER,fromBareJid, mContact.getName()!=null?mContact.getName():"", msg.getMbody(),
						    false, msg.getMtimestamp()));

//				    onLoadMore();
				    onAddMessage();
				    
				    
				    UnReadMsgNumber unReadMsgNumber = new UnReadMsgNumber();
				    unReadMsgNumber.setKey(StringUtils.parseBareAddress(fromBareJid));
				    unReadMsgNumber.setUnreadnumber(0);
				    duitangInfoAdapter.addUnReadMsgNumber(unReadMsgNumber);
				    
				}
			    }
			});
		}
	
		/**
		 * {@inheritDoc}.
		 */
		@Override
		public void stateChanged(IChat chat) throws RemoteException {
	
		}
	
		@Override
		public void otrStateChanged(final String otrState) throws RemoteException {
	
		}
    }
    
    private static final int HISTORY_MAX_SIZE = 5000;//最大可以显示5000条消息
	private int mcurrentPage = 0;//当前页码 1
	private int TotalCount;//总记录条数
	private int pageCount;//总页数
	
	private int dcurrentPage = 0;//1
	private int removeCount = 0;
	private int downremoveCount = 0;
	private int updcurrentPage = 0;
	
    public ImageMessageItem imgMessageItem;
    public FileMessageItem fileMessageItem;
    public VideoMessageItem videoMessageItem;
    public VoiceMessageItem voiceMessageItem;
    public TextMessageItem textMessageItem;
    public MapMessageItem mapMessageItem;
    public CardMessageItem cardMessageItem;
    public View view;
    public class StaggeredAdapter extends BaseAdapter {
        private Context mContext;
        private LinkedList<MessageText> mInfos;
//        private XListView mListView;
//        private IShareRefreshListView mListView;
//        private ChatListView mListView;
//        private int Listype = 1;//0普通图片listview 1瀑布流  2地图模式
        private MessageText duitangInfo = null;

        public StaggeredAdapter(Context context) {//
            mContext = context;
            mInfos = new LinkedList<MessageText>();
//            mListView = xListView;
//            Listype = uListype;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

        	ViewHolder holder;
        	duitangInfo = mInfos.get(position);
			if(duitangInfo.getMessage().startsWith("<transferfile mode=")
					|| duitangInfo.getMessage().startsWith("<transferfile transt='offline' mode=")){//文件
	            // 首先匹配img标签内的内容
	            String img_regex = "<(?i)transferfile(.*?)>(.*?)</(?i)transferfile>";//img
	            Pattern p = Pattern.compile(img_regex);
	            Matcher m = p.matcher(duitangInfo.getMessage());
	            
	            String src_alt;
	            String img_name;
	            String src_type="";
	            String filelength="";
	            while(m.find()){

	                src_alt=m.group(1);
	                img_name=m.group(2);
	                if(null==src_alt && null==img_name){
	                    continue;
	                }
	                
	                // 匹配src中的内容
	                String src_reg = "mode=\'(.*?)\'";//src
	                Pattern src_p = Pattern.compile(src_reg);
	                Matcher src_m = src_p.matcher(src_alt);
	                while(src_m.find()){
//	                    System.out.println("mode是：" + src_m.group(1));
	                }
	                
	                // 匹配alt中的内容
	                String alt_reg = "type=\'(.*?)\'";//alt
	                Pattern alt_p = Pattern.compile(alt_reg);
	                Matcher alt_m = alt_p.matcher(src_alt);
	                while(alt_m.find()){
//	                    System.out.println("type是：" + alt_m.group(1));
	                	src_type = alt_m.group(1);
	                	 System.out.println("type是：" +src_type);

	                }                
	                // 匹配filelength中的内容
	                String filelength_reg = "filelength=\'(.*?)\'";//alt
	                Pattern filelength_p = Pattern.compile(filelength_reg);
	                Matcher filelength_m = filelength_p.matcher(src_alt);
	                while(filelength_m.find()){
	                	filelength = filelength_m.group(1);
	                	System.out.println("时长:"+filelength+"秒");//录音时长
	                	
//	                    System.out.println("filelength是：" + filelength_m.group(1));
//	                    holder.text = (TextView) convertView.findViewById(R.id.chatting_content_itv);
//	                    holder.contentView.setText("时长:"+filelength_m.group(1)+"秒");//录音时长
	                } 
	                
//	 				File file = new File(img_name);
					String temp = img_name.substring(img_name.lastIndexOf(".")+1);
//					if( Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED) && file.exists() &&
					if( //file.exists() &&		
							(temp.equalsIgnoreCase("jpg")
							|| temp.equalsIgnoreCase("png")
							|| temp.equalsIgnoreCase("gif")
							|| temp.equalsIgnoreCase("bmp"))){
						//xmppConnectionAdapter.getAdaptee().getUser()
						imgMessageItem = new ImageMessageItem(mContext,duitangInfo,position,this,myjid,mContact.getJID(),null,(type==0?avatarpath:pic),"",ChatPullRefListActivity.this,username,"");
						imgMessageItem.registerConnectionStatusCallback(ChatPullRefListActivity.this);
						imgMessageItem.onFillMessage();
//						imgMessageItem.unRegisterConnectionStatusCallback();
						view = imgMessageItem.getRootView();
					}else{
						//img,audio,video,other
						if(src_type.equals("audio")){//amr
//							voiceMessageItem = new VoiceMessageItem(mContext,duitangInfo,position,this,xmppConnectionAdapter.getAdaptee().getUser(),mContact.getJIDWithRes());
							voiceMessageItem = new VoiceMessageItem(mContext,duitangInfo,position,this,myjid,mContact.getJID(),null,(type==0?avatarpath:pic),"",ChatPullRefListActivity.this,username,"");
							voiceMessageItem.onFillMessage();
				            view = voiceMessageItem.getRootView();
						}else if(src_type.equals("video")){
//							videoMessageItem = new VideoMessageItem(mContext,duitangInfo,position,this,xmppConnectionAdapter.getAdaptee().getUser(),mContact.getJIDWithRes());
							videoMessageItem = new VideoMessageItem(mContext,duitangInfo,position,this,myjid,mContact.getJID(),null,(type==0?avatarpath:pic),"",ChatPullRefListActivity.this,username,"");
							videoMessageItem.onFillMessage();
							view = videoMessageItem.getRootView();
						}else if(src_type.equals("map")){//map
							mapMessageItem = new MapMessageItem(mContext,duitangInfo,position,this,myjid,mContact.getJID(),(type==0?avatarpath:pic),"",ChatPullRefListActivity.this,username,"");
							mapMessageItem.onFillMessage();
							view = mapMessageItem.getRootView();
						}else{//file
//							fileMessageItem = new FileMessageItem(mContext,duitangInfo,position,this,xmppConnectionAdapter.getAdaptee().getUser(),mContact.getJIDWithRes());
							fileMessageItem = new FileMessageItem(mContext,duitangInfo,position,this,myjid,mContact.getJID(),null,(type==0?avatarpath:pic),"",ChatPullRefListActivity.this,username,"");
							fileMessageItem.onFillMessage();
							view = fileMessageItem.getRootView();
						}
					}
	            }
	            
			}else if(duitangInfo.getMessage().startsWith("<invite type=")){//名片
				cardMessageItem =  new CardMessageItem(mContext,duitangInfo,position,this,myjid,mContact.getJID(),(type==0?avatarpath:pic),"",ChatPullRefListActivity.this,username,"");
				cardMessageItem.onFillMessage();
				view = cardMessageItem.getRootView();
			}else{//文本文字
				textMessageItem = new TextMessageItem(mContext,duitangInfo,position,this,myjid,mContact.getJID(),(type==0?avatarpath:pic),"",ChatPullRefListActivity.this,username,"");
				textMessageItem.onFillMessage();
				view = textMessageItem.getRootView();
			}
			
			return view;
        }

        public class ViewHolder {
//            ScaleImageView imageView;
        	FlowView imageView;
            TextView contentView;
            TextView timeView;
            TextView nicknameView;
            TextView tvTime;//voice time
            ImageView animationIV;//voice Animation
            AnimationDrawable animationDrawable;
            String img_name;
//            HandyTextView message_tv_timestamp;//消息时间
        }
//        class TextViewListener implements OnClickListener{
////            private TextView contentView = null; 
//            private ViewHolder holder = null; 
//            private MESSAGE_TYPE message_type;
//            public TextViewListener( ViewHolder _holder,MESSAGE_TYPE _message_type) //TextView _contentView,
//            { 
//                // TODO Auto-generated constructor stub  
////                this.contentView = _contentView; 
//                this.holder = _holder; 
//                this.message_type = _message_type;
//            } 
//            @Override 
//            public void onClick(View v){ 
//				Log.e("※※※※※20140217语音播放动画start※※※※※", "※※语音播放动画start");
//				try{
//					holder.animationIV.setVisibility(View.VISIBLE);
//					if(duitangInfo.getMessageType()== MESSAGE_TYPE.SEND)
//						holder.animationIV.setImageResource(R.drawable.voice_from_icon_anim);
//					else
//						holder.animationIV.setImageResource(R.drawable.voice_to_icon_anim);
//					
//					holder.animationDrawable = (AnimationDrawable) holder.animationIV.getDrawable();  
//					holder.animationDrawable.start();
//					playMusic(holder.img_name,holder,message_type);
//				}catch(Exception e){
//					e.printStackTrace();
//				}
//            }
//        }

        @Override
        public int getCount() {
            return mInfos.size();
        }

        @Override
        public Object getItem(int arg0) {
            return mInfos.get(arg0);
        }

        @Override
        public long getItemId(int arg0) {
            return 0;
        }
        public void removeAll(){
        	mInfos.clear();
        	
        }
        public void addItemLast(List<MessageText> datas) {
        	if(datas!=null){
//            mInfos.addAll(datas);
            	for (MessageText info : datas) {
//                    if(!mInfos.contains(info))
//            		if(!contains(info.getBareJid()))
            		if(mInfos.size()>=HISTORY_MAX_SIZE){//仅缓存50条记录
            			mInfos.removeFirst();
            			downremoveCount++;//下拉效果需要
            		}
            		mInfos.addLast(info);
                }
            	Collections.sort(mInfos);
        	}
        }

        public void addItemTop(List<MessageText> datas) {
            if(datas!=null){
	        	for (MessageText info : datas) {
	//                if(!mInfos.contains(info))
	//        		if(!contains(info.getBareJid()))
	        		if(mInfos.size()>=HISTORY_MAX_SIZE){
	        			mInfos.removeLast();
	        			removeCount++;//上拉效果需要
	        		}
	        		mInfos.addFirst(info);
	            }
	        	Collections.sort(mInfos);
            }
        }
        public boolean contains(String key){
//        	for(int i=0;i<mInfos.size();i++){
        		Iterator<MessageText> it = mInfos.iterator();
        		MessageText di;
        		while(it.hasNext()){
        			di = it.next();
        		    if(di.getBareJid().equals(key))
        			return true;
        		}
//        	}
        	return false;
        }
        public void deleteMsg(int position){
        	try{
        		mInfos.remove(position);
        	}catch(Exception e){
        		e.printStackTrace();
        	}
        }
        
        public void update(int position,boolean _isUpload,boolean _isDownload,int _isOffline){
        	Log.e("※※※※※20140301更新上传或下载标识start※※※※※", "position="+position+";_isUpload="+_isUpload+";_isDownload="+_isDownload+";_isOffline="+_isOffline);
        	try{
	        	if(_isUpload)
	        		mInfos.get(position).setIsUpload(_isUpload);
	        	else if(_isDownload)
	        		mInfos.get(position).setIsDownload(_isDownload);
	        	mInfos.get(position).setIsOffline(_isOffline);
			    try {
			    	mChat = mChatManager.getChat(mContact);
				if (mChat == null) {
					
				    mChat = mChatManager.createChat(mContact, mMessageListener);
				    mChat.setOpen(true);
				    Log.e("※※※※※20170810(101010)※※※※※", "mChat.setOpen(true)");
				}
//				mChat.setOpen(true);
				Log.e("※※※※※####20140806####※※※※※", "※※数据库记录更新000(mChat!=null)※※"+(mChat!=null));
				if(_isUpload)
					mChat.updateMessage(position, 1,_isOffline,mInfos.get(position).getId());//UpDownType
				else if(!_isUpload)
					mChat.updateMessage(position, 0,_isOffline,mInfos.get(position).getId());//UpDownType
				else if(_isDownload)
					mChat.updateMessage(position, 2,_isOffline,mInfos.get(position).getId());//UpDownType
				else if(!_isDownload)
					mChat.updateMessage(position, 0,_isOffline,mInfos.get(position).getId());//UpDownType
			    } catch (RemoteException e) {
				Log.e(TAG, e.getMessage());
				Log.e("※※※※※####20140806####※※※※※", "※※数据库记录更新111※※"+e.getMessage());
			    }catch(Exception e){
			    	e.printStackTrace();
			    }
        	}catch(Exception e){
        		e.printStackTrace();
        		Log.e("※※※※※####20140806####※※※※※", "※※数据库记录更新222※※"+e.getMessage());
        	}
        }
    }
    
    private int mType = 0;//1 pulldown 2 pullup
    private List<MessageText> duitangs2 = new ArrayList<MessageText>();
    private int currentPage = 0;//0
    private List<com.stb.core.chat.Message> newMsgList = null;
    private List<MessageText> msgList = null;
    private int number = 0;
    public class LoadMoreTask extends AsyncTask<Void, Void, Boolean> {
//    	private PullToRefreshListView mPtrlv;
    	private int type = 0;
		public LoadMoreTask(int mtype) {
//			this.mPtrlv = ptrlv;
			this.type = mtype;
		}
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected Boolean doInBackground(Void... params) {
//            try {
//                Thread.sleep(1000);
//            } catch (InterruptedException e) {
//            }
//        	initContactList();
			duitangs2.clear();
			if (mChat != null) {
//				List<Message> newMsgList = null;
				try{
					newMsgList = mChat.getMessagesByPageIndex(pageSize, currentPage);//HISTORY_MAX_SIZE
				}catch(RemoteException e){
					return true;
				}catch(Exception e){
					return true;
				}
				if (newMsgList != null && newMsgList.size() > 0) {
//					if(yushu>0 && yushu<=newMsgList.size()){
//						for(int k=0;k<yushu;k++)
//							newMsgList.remove(k);
//					}
//					List<MessageText> msgList = convertMessagesList(newMsgList);
					msgList = convertMessagesList(newMsgList);
					duitangs2.addAll(msgList);
					number = newMsgList.size();
//					onAddNewDownMessage(number);
					newMsgList = null;
					msgList = null;
				}
			}
            return true;
        }

        @Override
        protected void onPostExecute(Boolean result) {
//            mAdapter.getMoreItem();
//            mAdapter.notifyDataSetChanged();
//            ptrstgv.getRefreshableView().hideFooterView();
            super.onPostExecute(result);
//            mAdapter.notifyDataSetChanged();
//            mPtrlv.onRefreshComplete();
			if (!result) {
//				showCustomToast("数据加载失败...");
				mHandler2.sendEmptyMessage(3);
			} else {
				mHandler2.sendEmptyMessage(0);
			}
        }

    }
	Handler mHandler2 = new Handler() {

		@Override
		public void handleMessage(android.os.Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case 0:
//				buildContactList(group);
				if(duitangs2.size()!=0 && mAdapter!=null){
					if(mType == 2)
						mAdapter.addItemLast(duitangs2);
					else if(mType == 1)
						mAdapter.addItemTop(duitangs2);
//	                mAdapter.addItemTop(duitangs2);
	                mAdapter.notifyDataSetChanged();
	                mListView.onRefreshCompleteHeader();
	                if(mType == 2)
	                	mListView.setSelection(mAdapter.getCount()-1);
	                else if(mType == 1)
	                	mListView.setSelection(duitangs2.size()-1);
//	                ptrlv.onRefreshComplete();
	                duitangs2.clear();
//					mAdapterView.onLoadMoreComplete();
				}
				mType = 0;
//				ptrlv.onRefreshComplete();
				break;
			case 1:
				mType = 0;
				mListView.onRefreshCompleteHeader();
				showCustomToast("已达顶端!");
				break;
			case 2:
				mType = 0;
				mListView.onRefreshCompleteHeader();
				showCustomToast("已达底端!");
				break;
//			case 8://定位成功
//				mLocationClient.stop();
//				dismissLoadingDialog();
//				showCustomToast("定位成功!经度:" + mLongitude + ",纬度:" + mLatitude + ",地址:" + mGpsAddr);
////				sendOfflineMap(BeemApplication.getInstance().mLongitude+"", BeemApplication.getInstance().mLatitude+"","map");
//				sendOfflineMap(mLongitude+"", mLatitude+"","map",mGpsAddr);
//				break;
//			case 9://定位失败
//				mLocationClient.stop();
//				dismissLoadingDialog();
//				showCustomToast("定位失败!");
//				break;				
			default:
				mType = 0;
				mListView.onRefreshCompleteHeader();
				break;
			}
		}

	};
	
    /**
     * Convert a list of Message coming from the service to a list of MessageText that can be displayed in UI.
     * @param chatMessages the list of Message
     * @return a list of message that can be displayed.
     */
    private MessageText tempMessageText = null;
    private List<MessageText> result = null;
    private MessageText lastMessage = null;
    private List<MessageText> convertMessagesList(List<com.stb.core.chat.Message> chatMessages) {
//    	MessageText tempMessageText = null;
//		List<MessageText> result = new ArrayList<MessageText>(chatMessages.size());
    	result = new ArrayList<MessageText>(chatMessages.size());
//		String remoteName = mContact.getName();
		String remoteName = mContact.getJID();
		String localName = getString(R.string.chat_self);
//		MessageText lastMessage = null;
	
		for (com.stb.core.chat.Message m : chatMessages) {
		    String name = remoteName;
//		    String fromBareJid = StringUtils.parseBareAddress(m.getFrom());
		    String fromBareJid = m.getMfrom();
//		    Log.e("++++++++20140605convertMessagesList++++++++","++++++++convertMessagesList++++++++fromBareJid="+fromBareJid);
//		    Log.e("++++++++20140605convertMessagesList++++++++","++++++++convertMessagesList++++++++remoteName="+remoteName);
		    if (m.getMtype() == com.stb.core.chat.Message.MSG_TYPE_ERROR) {
				lastMessage = null;
				tempMessageText = new MessageText(com.spice.im.chat.MessageText.MESSAGE_TYPE.RECEIVER,fromBareJid, name, m.getMbody(), true, m.getMtimestamp());
//				result.add(new MessageText(MESSAGE_TYPE.RECEIVER,fromBareJid, name, m.getBody(), true, m.getTimestamp()));
				tempMessageText.setIsOffline(1);
				tempMessageText.setId(m.getId());
				switch(m.getMupdowntype()){
				case 0:
					tempMessageText.setIsUpload(true);//special
					break;
				case 1:
					tempMessageText.setIsUpload(true);
					break;
				case 2:
					tempMessageText.setIsDownload(true);
					break;
				}
				result.add(tempMessageText);
		    } else if  (m.getMtype() == com.stb.core.chat.Message.MSG_TYPE_INFO) {
				lastMessage = new MessageText(com.spice.im.chat.MessageText.MESSAGE_TYPE.RECEIVER,"", "", m.getMbody(), false);
				lastMessage.setIsOffline(1);
				lastMessage.setId(m.getId());
				switch(m.getMupdowntype()){
				case 0:
					lastMessage.setIsUpload(true);//special
					break;
				case 1:
					lastMessage.setIsUpload(true);
					break;
				case 2:
					lastMessage.setIsDownload(true);
					break;
				}
				result.add(lastMessage);
	
		    } else if (m.getMtype() == com.stb.core.chat.Message.MSG_TYPE_CHAT) {
			if (fromBareJid == null) { //nofrom or from == yours
			    name = localName;
			    fromBareJid = "";
			}
	
			if (m.getMbody() != null) {
//				Log.e(TAG,"ChatActivity fromBareJid=" + fromBareJid+";remoteName="+remoteName+";StringUtils.parseName(fromBareJid)="+StringUtils.parseName(fromBareJid));
	//		    if (lastMessage == null || !fromBareJid.equals(lastMessage.getBareJid())) {
//				if(fromBareJid.equals("") || !StringUtils.parseName(fromBareJid).equals(remoteName))
//					lastMessage = new MessageText(MESSAGE_TYPE.SEND,fromBareJid, name, m.getBody(), false, m.getTimestamp());
//				else
				if((m.getMfrom()!=null && m.getMfrom().indexOf("@1")!=-1) || (m.getMto()!=null && m.getMto().indexOf("@1")!=-1)){//群聊
					lastMessage = new MessageText(com.spice.im.chat.MessageText.MESSAGE_TYPE.conference,fromBareJid, name, m.getMbody(), false, m.getMtimestamp());
				}else{
				if(StringUtils.parseName(fromBareJid).equals(StringUtils.parseName(remoteName)))
					lastMessage = new MessageText(com.spice.im.chat.MessageText.MESSAGE_TYPE.RECEIVER,fromBareJid, name, m.getMbody(), false, m.getMtimestamp());
				else
					lastMessage = new MessageText(com.spice.im.chat.MessageText.MESSAGE_TYPE.SEND,fromBareJid, name, m.getMbody(), false, m.getMtimestamp());
				}
				lastMessage.setId(m.getId());
				Log.e("※※※※※####20140807####※※※※※", "※※数据库记录m.getIsOffline()※※="+m.getMisoffline());
				switch(m.getMisoffline()){
				case 0:
					lastMessage.setIsOffline(0);
					break;
				case 1:
					lastMessage.setIsOffline(1);
					break;
				case 2:
					lastMessage.setIsOffline(2);
					break;
				}
//				lastMessage.setIsOffline(m.getIsOffline());
				switch(m.getMupdowntype()){
				case 0:
					lastMessage.setIsUpload(true);//special
					break;
				case 1:
					lastMessage.setIsUpload(true);
					break;
				case 2:
					lastMessage.setIsDownload(true);
					break;
				}
				result.add(lastMessage);
	//		    } else {
	//			lastMessage.setMessage(lastMessage.getMessage().concat("\n" + m.getBody()));
	//		    }
			}
		    }
		}
		return result;
    }
	public void onAddMessage() {
//		AddItemToContainer(++currentPage, 2 );
		Log.e(TAG,"ChatActivity onAddMessage");
		putAsyncTask(new AsyncTask<Void, Void, Boolean>() {
			@Override
			protected Boolean doInBackground(Void... params) {
//				try {
//					Thread.sleep(2000);
//				} catch (InterruptedException e) {
//				}
//				return null;
				return true;
			}
			@Override
			protected void onPostExecute(Boolean result) {
//				super.onPostExecute(result);
				if(duitangs2!=null && mAdapter!=null){
	                mAdapter.addItemLast(duitangs2);
	                mAdapter.notifyDataSetChanged();
	                mListView.setSelection(mAdapter.getCount()-1);
	                duitangs2.clear();
//					mAdapterView.onLoadMoreComplete();
				}
			}
		});
	}
	
	private class OnRightImageButtonClickListener implements
	onRightImageButtonClickListener {
	
		@Override
		public void onClick() {
//			getContactList(ConstantValues.refresh);
//			startActivity(new Intent(OtherProfileActivity.this, ContactFrameActivity.class));//ContactListPullRefListActivity
			Intent intent =  new Intent(ChatPullRefListActivity.this, ContactFrameActivity.class);
//	    	intent.putExtra("refreshroster", "true");
			intent.putExtra("jid",jid);
			intent.putExtra("contactuserid",jid);
			intent.putExtra("refreshlistviewonerow","1");
			startActivity(intent);
			ChatPullRefListActivity.this.finish();
		}
	}
	
	
//	@Override
//	public boolean onTouch(View v, MotionEvent event) {
//		Log.e("※※※※※ChatActivity onTouch start※※※※※", "※※ChatActivity onTouch start※※");
////		if (v.getId() == R.id.chat_textditor_eet_editer) {
////			mIbTextDitorKeyBoard.setVisibility(View.GONE);
////			mIbTextDitorEmote.setVisibility(View.VISIBLE);
////			showKeyBoard();
////		}
//		if (v.getId() == R.id.fullscreen_mask) {
//			if (event.getAction() == MotionEvent.ACTION_DOWN) {
////				hidePlusBar();
//			}
//		}
//		return false;
//	}
//	@Override
//	public void afterTextChanged(Editable s) {
//
//	}
//
//	@Override
//	public void beforeTextChanged(CharSequence s, int start, int count,
//			int after) {
//
//	}
//
//	@Override
//	public void onTextChanged(CharSequence s, int start, int before, int count) {
////		if (TextUtils.isEmpty(s)) {
////			mIvTextDitorAudio.setVisibility(View.VISIBLE);
////			mBtnTextDitorSend.setVisibility(View.GONE);
////		} else {
////			mIvTextDitorAudio.setVisibility(View.GONE);
////			mBtnTextDitorSend.setVisibility(View.VISIBLE);
////		}
//		
//    	voice_text.setVisibility(View.GONE);
//    	mInputView.setVisibility(View.VISIBLE);
////        image_voice.setVisibility(View.GONE);
//        image_keyboard.setVisibility(View.GONE);
//        if (s.length() > 0) {
//            send.setVisibility(View.VISIBLE);
//            image_voice.setVisibility(View.GONE);
//        } else {
//            send.setVisibility(View.GONE);
//            image_voice.setVisibility(View.VISIBLE);
//        }
//	}
	
	Uri uri = null;
	//利用requestCode区别开不同的返回结果
	//resultCode参数对应于子模块中setResut(int resultCode, Intent intent)函数中的resultCode值，用于区别不同的返回结果（如请求正常、请求异常等）
	//对应流程：
	//母模块startActivityForResult--触发子模块，根据不同执行结果设定resucode值，最后执行setResut并返回到木模块--母模块触发onActivityResult，根据requestcode参数区分不同子模块。
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode==3 && resultCode==3 && data!=null){
        	//地图定位
        	String locationpath = data.getStringExtra("locationpath");
//        	Toast.makeText(ChatPullRefListActivity.this, "20200328locationpath="+locationpath, Toast.LENGTH_LONG).show();
        	if(locationpath!=null 
        			&& !locationpath.equalsIgnoreCase("null")
        			&& locationpath.length()!=0){
        		String[] xy = locationpath.split(","); 
        		if(xy!=null && xy.length==3){
	        		String mLongitude = xy[0];
	        		String mLatitude = xy[1];
	        		String mGpsAddr = xy[2];
	        		sendOfflineMap(mLongitude,mLatitude,"map",mGpsAddr);
        		}else{
        			showCustomToast("定位失败,稍候再试...");
        		}
        	}
        }else if(requestCode==2 && resultCode==2 && data!=null){
        	String filepath = data.getStringExtra("filepath");
//        	Toast.makeText(ChatPullRefListActivity.this, "filepath="+filepath, Toast.LENGTH_LONG).show();
			if(filepath.length() > 0){
//				sendFile(filepath);//P2P send file
				File file = new File(filepath);
				if (file.exists() && file.canRead()) {
					sendOfflineFile(filepath,"file");//send offline file via agent file server 
								    
				} else {
					Toast.makeText(ChatPullRefListActivity.this, "file not exists", Toast.LENGTH_LONG).show();
//					Toast.makeText(ChatPullRefListActivity.this, "user="+xmppConnectionAdapter.getAdaptee().getUser(), Toast.LENGTH_LONG).show();//from
					Toast.makeText(ChatPullRefListActivity.this, "user="+myjid, Toast.LENGTH_LONG).show();//from
					Toast.makeText(ChatPullRefListActivity.this, "getJID="+mContact.getJID(), Toast.LENGTH_LONG).show();//to
//					Toast.makeText(Chat.this, "getJID="+mChat.getAccountUser(), Toast.LENGTH_LONG).show();
					
					try{
//					Toast.makeText(Chat.this, "getJID="+mContact.getJIDWithRes()+";getParticipant="+mChat.getParticipant().getJIDWithRes(), Toast.LENGTH_LONG).show();
					Toast.makeText(ChatPullRefListActivity.this, "getJID="+mChat.getParticipant().getJID(), Toast.LENGTH_LONG).show();
					}catch(Exception e){}
				}
			}
        }
        else if ( requestCode == GalleryHelper.GALLERY_REQUEST_CODE) {
            if ( resultCode == GalleryHelper.GALLERY_RESULT_SUCCESS ) {
                PhotoInfo photoInfo = data.getParcelableExtra(GalleryHelper.RESULT_DATA);
                List<PhotoInfo> photoInfoList = (List<PhotoInfo>) data.getSerializableExtra(GalleryHelper.RESULT_LIST_DATA);

                if ( photoInfo != null ) {
//                    ImageLoader.getInstance().displayImage("file:/" + photoInfo.getPhotoPath(), mIvResult);
                    uri = Uri.parse("file:/" + photoInfo.getPhotoPath());
                    Toast.makeText(this, "选择了照片路径:" + photoInfo.getPhotoPath(), Toast.LENGTH_SHORT).show();
                    sendOfflineFile(photoInfo.getPhotoPath(),"img");
                }

                if ( photoInfoList != null ) {
                    Toast.makeText(this, "选择了" + photoInfoList.size() + "张", Toast.LENGTH_SHORT).show();
                }
            }
        }
        else if ( requestCode == GalleryHelper.TAKE_REQUEST_CODE ) {
            if (resultCode == RESULT_OK && mTakePhotoUri != null) {
                final String path = mTakePhotoUri.getPath();
                final PhotoInfo info = new PhotoInfo();
                info.setPhotoPath(path);
//                updateGallery(path);

                final int degress = BitmapUtils.getDegress(path);
                if (degress != 0) {
                    new AsyncTask<Void, Void, Void>() {

                        @Override
                        protected void onPreExecute() {
                            super.onPreExecute();
                            toast("请稍等…");
                        }

                        @Override
                        protected Void doInBackground(Void... params) {
                            try {
                                Bitmap bitmap = rotateBitmap(path, degress);
                                saveRotateBitmap(bitmap, path);
                                bitmap.recycle();
                            } catch (Exception e) {
                                Logger.e(e);
                            }
                            return null;
                        }

                        @Override
                        protected void onPostExecute(Void voids) {
                            super.onPostExecute(voids);
//                            takeResult(info);
                            toPhotoCrop(info);
                        }
                    }.execute();
                } else {
//                    takeResult(info);
                	toPhotoCrop(info);
                }
            } else {
                toast("拍照失败");
            }
        } else if ( requestCode == GalleryHelper.CROP_REQUEST_CODE) {
            if ( resultCode == GalleryHelper.CROP_SUCCESS ) {
                PhotoInfo photoInfo = data.getParcelableExtra(GalleryHelper.RESULT_DATA);
                resultSingle(photoInfo);
            }
        } else if ( requestCode == GalleryHelper.GALLERY_RESULT_SUCCESS ) {
            PhotoInfo photoInfo = data.getParcelableExtra(GalleryHelper.RESULT_DATA);
            List<PhotoInfo> photoInfoList = (List<PhotoInfo>) data.getSerializableExtra(GalleryHelper.RESULT_LIST_DATA);

            if ( photoInfo != null ) {
//                ImageLoader.getInstance().displayImage("file:/" + photoInfo.getPhotoPath(), mIvResult);
                uri = Uri.parse("file:/" + photoInfo.getPhotoPath());
                Toast.makeText(this, "选择了照片路径:" + photoInfo.getPhotoPath(), Toast.LENGTH_SHORT).show();
                sendOfflineFile(photoInfo.getPhotoPath(),"img");
            }

            if ( photoInfoList != null ) {
                Toast.makeText(this, "选择了" + photoInfoList.size() + "张", Toast.LENGTH_SHORT).show();
            }
        } else if(requestCode == REQUEST_VIDEO_CODE){//选择视频文件上传
//        	Toast.makeText(this, "选择了视频111", Toast.LENGTH_SHORT).show();
            if (resultCode == RESULT_OK) {
//            	Toast.makeText(this, "选择了视频222", Toast.LENGTH_SHORT).show();
//                try {
//                    Uri uri = data.getData();
////                    uri = BitmapCache.geturi(this, data);
////                    path = getPath(uri);
////                    File file = new File(path);
////                    if (!file.exists()) {
////                        break;
////                    }
////                    if (file.length() > 100 * 1024 * 1024) {
////                        commonToast("文件大于100M");
////                        break;
////                    }
////                    //传换文件流，上传
////                    submitVedio();
//                    ContentResolver cr = this.getContentResolver();
//                    /** 数据库查询操作。
//                     * 第一个参数 uri：为要查询的数据库+表的名称。
//                     * 第二个参数 projection ： 要查询的列。
//                     * 第三个参数 selection ： 查询的条件，相当于SQL where。
//                     * 第三个参数 selectionArgs ： 查询条件的参数，相当于 ？。
//                     * 第四个参数 sortOrder ： 结果排序。
//                     */
//                    String[] proj = {MediaStore.Video.Media.DATA};
//                    Cursor cursor = cr.query(uri, proj, null, null, null);
//                    if (cursor != null) {
//                    	Toast.makeText(this, "选择了视频555", Toast.LENGTH_SHORT).show();
//                        if (cursor.moveToFirst()) {
//                        	Toast.makeText(this, "选择了视频666", Toast.LENGTH_SHORT).show();
////                            // 视频ID:MediaStore.Audio.Media._ID
////                            int videoId = cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Video.Media._ID));
////                            // 视频名称：MediaStore.Audio.Media.TITLE
////                            String title = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.TITLE));
////                            // 视频路径：MediaStore.Audio.Media.DATA
////                            String videoPath = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA));
////                            // 视频时长：MediaStore.Audio.Media.DURATION
////                            int duration = cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DURATION));
////                            // 视频大小：MediaStore.Audio.Media.SIZE
////                            long size = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.SIZE));
////                            
////                            if(size > 100 * 1024 * 1024){
////                            	Toast.makeText(this, "文件大于100M", Toast.LENGTH_SHORT).show();
////                            }else{
////                            	Toast.makeText(this, "选择了视频路径:" + videoPath, Toast.LENGTH_SHORT).show();
////                                sendOfflineFile(videoPath,"video");
////                            }
//                        	String v_path = cursor.getString(1); // 图片文件路径  
//                            String v_size = cursor.getString(2); // 图片大小  
//                            String v_name = cursor.getString(3); // 图片文件名  
//                            Toast.makeText(this, "选择了视频路径:" +v_size+";"+ v_path, Toast.LENGTH_SHORT).show();
//                            sendOfflineFile(v_path,"video");
//                        }
//                        cursor.close();
//                    }else{
//                    	Toast.makeText(this, "选择了视频777", Toast.LENGTH_SHORT).show();
//                    }
//                } catch (Exception e) {
//                	Toast.makeText(this, "选择了视频333", Toast.LENGTH_SHORT).show();
//                  } catch (OutOfMemoryError e) {
//                	  Toast.makeText(this, "选择了视频444", Toast.LENGTH_SHORT).show();
//                   }
            	
            	
            	
//            	String path = "";
//                try {
//                    Uri uri = data.getData();
//                    uri = geturi(this, data);
//                    File file = null;
//                    if (uri.toString().indexOf("file") == 0) {
//                        file = new File(new URI(uri.toString()));
//                        path = file.getPath();
//                    } else {
//                        path = getPath(uri);
//                        file = new File(path);
//                    }
//                    if (!file.exists()) {
////                        break;
//                    	Toast.makeText(this, "文件不存在.", Toast.LENGTH_SHORT).show();
//                    }
//                    else if (file.length() > 100 * 1024 * 1024) {
////                        "文件大于100M";
////                        break;
//                    	Toast.makeText(this, "文件大于100M.", Toast.LENGTH_SHORT).show();
//                    }else{
////                    //视频播放
////                    mVideoView.setVideoURI(uri);
////                    mVideoView.start();
//                    //开始上传视频，
////                    submitVedio();
//                    	sendOfflineFile(path,"video");
//                    }
//                } catch (Exception e) {
//                    String  a=e+"";
//                } catch (OutOfMemoryError e) {
//                    String  a=e+"";
//                }
            	
            	String path = "";
            	if (data != null) {    
            	    Uri uri = data.getData();    
            	    if (!TextUtils.isEmpty(uri.getAuthority())) {    
            	        Cursor cursor = getContentResolver().query(uri,  
            	                new String[] { MediaStore.Video.Media.DATA },null, null, null);    
            	        if (null == cursor) {    
            	            Toast.makeText(this, "未找到视频", Toast.LENGTH_SHORT).show();    
            	            return;    
            	        }    
            	        cursor.moveToFirst();    
            	        path = cursor.getString(cursor.getColumnIndex(MediaStore.Video.Media.DATA));  
            	        cursor.close();    
            	    } else {    
            	        path = uri.getPath();    //android 2.1
//            	        path = getPath(this, uri);//android 4.4
            	    } 
//            	    Toast.makeText(this, "视频"+path, Toast.LENGTH_SHORT).show(); 
            	    sendOfflineFile(path,"video");
            	}else{    
            	    Toast.makeText(this, "未找到视频", Toast.LENGTH_SHORT).show();    
            	    return;    
            	} 
            }
        }
        
    }
//    // 4.4 满足android4.4以上获取文件bug  start
//    @SuppressLint("NewApi")
//	public String getPath(final Context context, final Uri uri) {
//
//        final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
//
//        // DocumentProvider
//        if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
//            // ExternalStorageProvider
//            if (isExternalStorageDocument(uri)) {
//                final String docId = DocumentsContract.getDocumentId(uri);
////                Log.i(TAG,"isExternalStorageDocument***"+uri.toString());
////                Log.i(TAG,"docId***"+docId);
////                以下是打印示例：
////                isExternalStorageDocument***content://com.android.externalstorage.documents/document/primary%3ATset%2FROC2018421103253.wav
////                docId***primary:Test/ROC2018421103253.wav
//                final String[] split = docId.split(":");
//                final String type = split[0];
//
//                if ("primary".equalsIgnoreCase(type)) {
//                    return Environment.getExternalStorageDirectory() + "/" + split[1];
//                }
//            }
//            // DownloadsProvider
//            else if (isDownloadsDocument(uri)) {
////                Log.i(TAG,"isDownloadsDocument***"+uri.toString());
//                final String id = DocumentsContract.getDocumentId(uri);
//                final Uri contentUri = ContentUris.withAppendedId(
//                        Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
//
//                return getDataColumn(context, contentUri, null, null);
//            }
//            // MediaProvider
//            else if (isMediaDocument(uri)) {
////                Log.i(TAG,"isMediaDocument***"+uri.toString());
//                final String docId = DocumentsContract.getDocumentId(uri);
//                final String[] split = docId.split(":");
//                final String type = split[0];
//
//                Uri contentUri = null;
//                if ("image".equals(type)) {
//                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
//                } else if ("video".equals(type)) {
//                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
//                } else if ("audio".equals(type)) {
//                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
//                }
//
//                final String selection = "_id=?";
//                final String[] selectionArgs = new String[]{split[1]};
//
//                return getDataColumn(context, contentUri, selection, selectionArgs);
//            }
//        }
//        // MediaStore (and general)
//        else if ("content".equalsIgnoreCase(uri.getScheme())) {
////            Log.i(TAG,"content***"+uri.toString());
//            return getDataColumn(context, uri, null, null);
//        }
//        // File
//        else if ("file".equalsIgnoreCase(uri.getScheme())) {
////            Log.i(TAG,"file***"+uri.toString());
//            return uri.getPath();
//        }
//        return null;
//    }
//
//    /**
//     * Get the value of the data column for this Uri. This is useful for
//     * MediaStore Uris, and other file-based ContentProviders.
//     *
//     * @param context       The context.
//     * @param uri           The Uri to query.
//     * @param selection     (Optional) Filter used in the query.
//     * @param selectionArgs (Optional) Selection arguments used in the query.
//     * @return The value of the _data column, which is typically a file path.
//     */
//    public String getDataColumn(Context context, Uri uri, String selection,
//                                String[] selectionArgs) {
//
//        Cursor cursor = null;
//        final String column = "_data";
//        final String[] projection = {column};
//
//        try {
//            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
//                    null);
//            if (cursor != null && cursor.moveToFirst()) {
//                final int column_index = cursor.getColumnIndexOrThrow(column);
//                return cursor.getString(column_index);
//            }
//        } finally {
//            if (cursor != null)
//                cursor.close();
//        }
//        return null;
//    }
//
//    
//    public boolean isExternalStorageDocument(Uri uri) {
//        return "com.android.externalstorage.documents".equals(uri.getAuthority());
//    }
//    
//    public boolean isDownloadsDocument(Uri uri) {
//        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
//    }
//
//    public boolean isMediaDocument(Uri uri) {
//        return "com.android.providers.media.documents".equals(uri.getAuthority());
//    }
//    // 4.4 满足android4.4以上获取文件bug  end
    
    
    //recodeTime
    String transformfilepath = "";
    String transformfiletype = "";
    private void sendOfflineFile(String filepath,String type) {
		
    	transformfilepath = filepath;
    	transformfiletype = type;
    	
		try{
    		File file2 = new File(transformfilepath);
    		if(file2.exists()){
    			String sendStr = "<transferfile transt='offline' mode='send' type='"+transformfiletype+"' filelength='"+(int)recodeTime+"' filesize='"+file2.length()+"'>"+transformfilepath+"</transferfile>";
    			final String self = getString(R.string.chat_self);
//    			com.stb.core.chat.Message msgToSend = new com.stb.core.chat.Message(self, com.stb.core.chat.Message.MSG_TYPE_CHAT);
    			com.stb.core.chat.Message msgToSend = new com.stb.core.chat.Message(StringUtils.parseBareAddress(mContact.getJID()), com.stb.core.chat.Message.MSG_TYPE_CHAT);
    			
			    msgToSend.setMbody("<transferfile transt='offline' mode='send' type='"+transformfiletype+"' filelength='"+(int)recodeTime+"' filesize='"+file2.length()+"'>"+transformfilepath+"</transferfile>");
			    msgToSend.setMupdowntype(1);//0 other,1 upload,2 download
			    
			    if(mContact.getJID().indexOf("@1")!=-1)//群组消息的话，mfrom为 "群组的tagid@1/用户的uid，即 tagid@1/uid"
			    	msgToSend.setMfrom(StringUtils.parseBareAddress(mContact.getJID())+"/"+StringUtils.parseBareAddress2(myjid));
			    else
			    	msgToSend.setMfrom(myjid);
			    
			    int id = 0;
			    boolean except = false;
			    try {
	//			    	mChat = mChatManager.getChat(mContact);
					if (mChat == null) {
						
					    mChat = mChatManager.createChat(mContact, mMessageListener);
					    mChat.setOpen(true);
					    Log.e("※※※※※20170810(111111)※※※※※", "mChat.setOpen(true)");
					}
	//				mChat.setOpen(true);
					id = mChat.addMessage(msgToSend);
					Log.e("※※※※※####20140807####※※※※※", "※※数据库非群聊chatpull00 logMessage id = ※※:"+id);
			    } catch (RemoteException e) {
			    	except = true;
					Log.e(TAG, e.getMessage());
					XmppConnectionAdapter.saveAsOfflineMessage(getContentResolver(), mContact.getJID(), sendStr);
					msgToSend.setMisoffline(2);//mIsOffline 0 other发送中,1 false notoffline发送成功, 2true 发送失败isoffline
					chatAdapterOffline.addMessage(AccountUser, Participant, msgToSend);//如果断开了连接（无论是服务器宕机还是客户端本身问题）记录到本地sqlite中存储的聊天记录，供聊天窗口展示
			    }catch(Exception e){
			    	except = true;
			    	e.printStackTrace();
					XmppConnectionAdapter.saveAsOfflineMessage(getContentResolver(), mContact.getJID(), sendStr);
					msgToSend.setMisoffline(2);//mIsOffline 0 other发送中,1 false notoffline发送成功, 2true 发送失败isoffline
					chatAdapterOffline.addMessage(AccountUser, Participant, msgToSend);//如果断开了连接（无论是服务器宕机还是客户端本身问题）记录到本地sqlite中存储的聊天记录，供聊天窗口展示
			    }
//    			}
			    System.out.println("===============20130715(3)mMessageListener="+mMessageListener+";mContact="+mContact+";mChatManager="+mChatManager+"===============");
				//"Me", "Me",
//			    duitangs2.add(new MessageText(MESSAGE_TYPE.SEND,self, self, "<transferfile transt='offline' mode='send' type='"+transformfiletype+"' filelength='"+(int)recodeTime+"' filesize='"+file2.length()+"'>"+transformfilepath+"</transferfile>", false, new Date()));
//			    MessageText temp = new MessageText(com.spice.im.chat.MessageText.MESSAGE_TYPE.SEND,self, self, "<transferfile transt='offline' mode='send' type='"+transformfiletype+"' filelength='"+(int)recodeTime+"' filesize='"+file2.length()+"'>"+transformfilepath+"</transferfile>", false, new Date());
			    MessageText temp = null;
			    temp = new MessageText(com.spice.im.chat.MessageText.MESSAGE_TYPE.SEND,msgToSend.getMfrom(), self, "<transferfile transt='offline' mode='send' type='"+transformfiletype+"' filelength='"+(int)recodeTime+"' filesize='"+file2.length()+"'>"+transformfilepath+"</transferfile>", false, new Date());
			    temp.setId(id);
			    if(except)
			    	temp.setIsOffline(2);
			    else
			    	temp.setIsOffline(1);
			    Log.e("※※※※※####20140807####※※※※※", "※※数据库非群聊chatpull22 logMessage id = ※※:"+id +";temp.getId()="+temp.getId());
			    duitangs2.add(temp);
			    onAddMessage();
    				
    				
    			}
    		
		}catch(Exception e){
			e.printStackTrace();
		}
		
	}
    
    
    /**
     * 拍照
     */
    String mPhotoTargetFolder = null;
    Uri mTakePhotoUri = null;
    protected void takePhotoAction() {

        if (!DeviceUtils.existSDCard()) {
//            toast("没有SD卡不能拍照呢~");
        	Toast.makeText(this, "没有SD卡不能拍照呢~", Toast.LENGTH_SHORT).show();
            return;
        }

        File takePhotoFolder = null;
        if (cn.finalteam.toolsfinal.StringUtils.isEmpty(mPhotoTargetFolder)) {
            takePhotoFolder = new File(Environment.getExternalStorageDirectory(),
                    "/DCIM/" + GalleryHelper.TAKE_PHOTO_FOLDER);
        } else {
            takePhotoFolder = new File(mPhotoTargetFolder);
        }

        File toFile = new File(takePhotoFolder, "IMG" + DateUtils.format(new Date(), "yyyyMMddHHmmss") + ".jpg");
        boolean suc = FileUtils.makeFolders(toFile);
        Logger.d("create folder=" + toFile.getAbsolutePath());
        if (suc) {
            mTakePhotoUri = Uri.fromFile(toFile);
            Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, mTakePhotoUri);
            startActivityForResult(captureIntent, GalleryHelper.TAKE_REQUEST_CODE);
        }
    }
    protected int mScreenWidth = 720;
    protected int mScreenHeight = 1280;
    protected Bitmap rotateBitmap(String path, int degress) {
        try {
            Bitmap bitmap = BitmapUtils.compressBitmap(path, mScreenWidth / 4, mScreenHeight / 4);
            bitmap = BitmapUtils.rotateBitmap(bitmap, degress);
            return bitmap;
        } catch (Exception e) {
            Logger.e(e);
        }

        return null;
    }

    protected void saveRotateBitmap(Bitmap bitmap, String path) {
        //保存
        BitmapUtils.saveBitmap(bitmap, new File(path));
        //修改数据库
        ContentValues cv = new ContentValues();
        cv.put("orientation", 0);
        ContentResolver cr = getContentResolver();
        String where = new String(MediaStore.Images.Media.DATA + "='" + cn.finalteam.toolsfinal.StringUtils.sqliteEscape(path) +"'");
        cr.update(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, cv, where, null);
    }
    public void toast(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }
    protected void resultSingle(PhotoInfo photoInfo) {
//        Intent intent = getIntent();
//        if (intent == null) {
//            intent = new Intent();
//        }
//        intent.putExtra(GalleryHelper.RESULT_DATA, photoInfo);
////        setResult(GalleryHelper.GALLERY_RESULT_SUCCESS, intent);
////        finish();
//        startActivityForResult(intent, GalleryHelper.GALLERY_RESULT_SUCCESS);
    	
        if ( photoInfo != null ) {
//          ImageLoader.getInstance().displayImage("file:/" + photoInfo.getPhotoPath(), mIvResult);
          uri = Uri.parse("file:/" + photoInfo.getPhotoPath());
          Toast.makeText(this, "选择了照片路径:" + photoInfo.getPhotoPath(), Toast.LENGTH_SHORT).show();
          sendOfflineFile(photoInfo.getPhotoPath(),"img");
      }
    }
    /**
     * 执行裁剪
     */
    protected void toPhotoCrop(PhotoInfo info) {
        Intent intent = new Intent(this, PhotoCropActivity.class);
        intent.putExtra(PhotoCropActivity.PHOTO_INFO, info);
        startActivityForResult(intent, GalleryHelper.CROP_REQUEST_CODE);
    }
    
    
    //发送位置地图start   type=map
    private void sendOfflineMap(String mLongitude,String mLatitude,String type,String mGpsAddr) {
		
    	transformfiletype = type;
    	
		try{
    		    String sendStr = "<transferfile transt='offline' mode='send' type='"+transformfiletype+"' filelength='"+(int)recodeTime+"' filesize='0'>"+mLongitude+","+mLatitude+","+mGpsAddr+"</transferfile>";
    			final String self = getString(R.string.chat_self);
//    			com.stb.core.chat.Message msgToSend = new com.stb.core.chat.Message(self, com.stb.core.chat.Message.MSG_TYPE_CHAT);
    			com.stb.core.chat.Message msgToSend = new com.stb.core.chat.Message(StringUtils.parseBareAddress(mContact.getJID()), com.stb.core.chat.Message.MSG_TYPE_CHAT);
    			
			    msgToSend.setMbody("<transferfile transt='offline' mode='send' type='"+transformfiletype+"' filelength='"+(int)recodeTime+"' filesize='0'>"+mLongitude+","+mLatitude+","+mGpsAddr+"</transferfile>");
			    msgToSend.setMupdowntype(1);//0 other,1 upload,2 download
			    
			    if(mContact.getJID().indexOf("@1")!=-1)//群组消息的话，mfrom为 "群组的tagid@1/用户的uid，即 tagid@1/uid"
			    	msgToSend.setMfrom(StringUtils.parseBareAddress(mContact.getJID())+"/"+StringUtils.parseBareAddress2(myjid));
			    else
			    	msgToSend.setMfrom(myjid);
			    
			    int id = 0;
			    boolean except = false;
			    try {
	//			    	mChat = mChatManager.getChat(mContact);
					if (mChat == null) {
						
					    mChat = mChatManager.createChat(mContact, mMessageListener);
					    mChat.setOpen(true);
					    Log.e("※※※※※20170810(111111)※※※※※", "mChat.setOpen(true)");
					}
	//				mChat.setOpen(true);
	//				id = mChat.addMessage(msgToSend);
					id = mChat.sendMessage(msgToSend);
					Log.e("※※※※※####20140807####※※※※※", "※※数据库非群聊chatpull00 logMessage id = ※※:"+id);
			    } catch (RemoteException e) {
			    	except = true;
					Log.e(TAG, e.getMessage());
					XmppConnectionAdapter.saveAsOfflineMessage(getContentResolver(), mContact.getJID(), sendStr);//待自动重发的消息
					msgToSend.setMisoffline(2);//mIsOffline 0 other发送中,1 false notoffline发送成功, 2true 发送失败isoffline
					chatAdapterOffline.addMessage(AccountUser, Participant, msgToSend);//如果断开了连接（无论是服务器宕机还是客户端本身问题）记录到本地sqlite中存储的聊天记录，供聊天窗口展示
			    
			    }catch(Exception e){
			    	except = true;
			    	e.printStackTrace();
			    	XmppConnectionAdapter.saveAsOfflineMessage(getContentResolver(), mContact.getJID(), sendStr);//待自动重发的消息
					msgToSend.setMisoffline(2);//mIsOffline 0 other发送中,1 false notoffline发送成功, 2true 发送失败isoffline
					chatAdapterOffline.addMessage(AccountUser, Participant, msgToSend);//如果断开了连接（无论是服务器宕机还是客户端本身问题）记录到本地sqlite中存储的聊天记录，供聊天窗口展示
			    
			    }
//    			}
			    System.out.println("===============20130715(3)mMessageListener="+mMessageListener+";mContact="+mContact+";mChatManager="+mChatManager+"===============");
				//"Me", "Me",
//			    duitangs2.add(new MessageText(MESSAGE_TYPE.SEND,self, self, "<transferfile transt='offline' mode='send' type='"+transformfiletype+"' filelength='"+(int)recodeTime+"' filesize='"+file2.length()+"'>"+transformfilepath+"</transferfile>", false, new Date()));
//			    MessageText temp = new MessageText(com.spice.im.chat.MessageText.MESSAGE_TYPE.SEND,self, self, "<transferfile transt='offline' mode='send' type='"+transformfiletype+"' filelength='"+(int)recodeTime+"' filesize='"+file2.length()+"'>"+transformfilepath+"</transferfile>", false, new Date());
			    MessageText temp = null;
			    temp = new MessageText(com.spice.im.chat.MessageText.MESSAGE_TYPE.SEND,msgToSend.getMfrom(), self, "<transferfile transt='offline' mode='send' type='"+transformfiletype+"' filelength='"+(int)recodeTime+"' filesize='0'>"+mLongitude+","+mLatitude+","+mGpsAddr+"</transferfile>", false, new Date());
			    temp.setId(id);
			    if(except)
			    	temp.setIsOffline(2);
			    else
			    	temp.setIsOffline(1);
			    Log.e("※※※※※####20140807####※※※※※", "※※数据库非群聊chatpull22 logMessage id = ※※:"+id +";temp.getId()="+temp.getId());
			    duitangs2.add(temp);
			    onAddMessage();
    				
    				
    			
    		
		}catch(Exception e){
			e.printStackTrace();
		}
		
	}
    //发送位置地图end
    
    
//	/**
//	 * 根据Uri获取图片绝对路径，解决Android4.4以上版本Uri转换
//	 * @param activity
//	 * @param imageUri
//	 * @author yaoxing
//	 * @date 2014-10-12
//	 */
//	//@TargetApi(19)
//	public static String getImageAbsolutePath(Activity context, Uri imageUri) {
//		if (context == null || imageUri == null)
//			return null;
//		if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT && DocumentsContract.isDocumentUri(context, imageUri)) {
//			if (isExternalStorageDocument(imageUri)) {
//				String docId = DocumentsContract.getDocumentId(imageUri);
//				String[] split = docId.split(":");
//				String type = split[0];
//				if ("primary".equalsIgnoreCase(type)) {
//					return Environment.getExternalStorageDirectory() + "/" + split[1];
//				}
//			} else if (isDownloadsDocument(imageUri)) {
//				String id = DocumentsContract.getDocumentId(imageUri);
//				Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
//				return getDataColumn(context, contentUri, null, null);
//			} else if (isMediaDocument(imageUri)) {
//				String docId = DocumentsContract.getDocumentId(imageUri);
//				String[] split = docId.split(":");
//				String type = split[0];
//				Uri contentUri = null;
//				if ("image".equals(type)) {
//					contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
//				} else if ("video".equals(type)) {
//					contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
//				} else if ("audio".equals(type)) {
//					contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
//				}
//				String selection = MediaStore.Images.Media._ID + "=?";
//				String[] selectionArgs = new String[] { split[1] };
//				return getDataColumn(context, contentUri, selection, selectionArgs);
//			}
//		} // MediaStore (and general)
//		else if ("content".equalsIgnoreCase(imageUri.getScheme())) {
//			// Return the remote address
//			if (isGooglePhotosUri(imageUri))
//				return imageUri.getLastPathSegment();
//			return getDataColumn(context, imageUri, null, null);
//		}
//		// File
//		else if ("file".equalsIgnoreCase(imageUri.getScheme())) {
//			return imageUri.getPath();
//		}
//		return null;
//	}
//
//	public static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
//		Cursor cursor = null;
//		String column = MediaStore.Images.Media.DATA;
//		String[] projection = { column };
//		try {
//			cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
//			if (cursor != null && cursor.moveToFirst()) {
//				int index = cursor.getColumnIndexOrThrow(column);
//				return cursor.getString(index);
//			}
//		} finally {
//			if (cursor != null)
//				cursor.close();
//		}
//		return null;
//	}
//
//	/**
//	 * @param uri The Uri to check.
//	 * @return Whether the Uri authority is ExternalStorageProvider.
//	 */
//	public static boolean isExternalStorageDocument(Uri uri) {
//		return "com.android.externalstorage.documents".equals(uri.getAuthority());
//	}
//
//	/**
//	 * @param uri The Uri to check.
//	 * @return Whether the Uri authority is DownloadsProvider.
//	 */
//	public static boolean isDownloadsDocument(Uri uri) {
//		return "com.android.providers.downloads.documents".equals(uri.getAuthority());
//	}
//
//	/**
//	 * @param uri The Uri to check.
//	 * @return Whether the Uri authority is MediaProvider.
//	 */
//	public static boolean isMediaDocument(Uri uri) {
//		return "com.android.providers.media.documents".equals(uri.getAuthority());
//	}
//
//	/**
//	 * @param uri The Uri to check.
//	 * @return Whether the Uri authority is Google Photos.
//	 */
//	public static boolean isGooglePhotosUri(Uri uri) {
//		return "com.google.android.apps.photos.content".equals(uri.getAuthority());
//	}
    
    public static Uri geturi(Context context, android.content.Intent intent) {
        Uri uri = intent.getData();
        String type = intent.getType();
        if (uri.getScheme().equals("file") && (type.contains("image/"))) {
            String path = uri.getEncodedPath();
            if (path != null) {
                path = Uri.decode(path);
                ContentResolver cr = context.getContentResolver();
                StringBuffer buff = new StringBuffer();
                buff.append("(").append(MediaStore.Images.ImageColumns.DATA).append("=")
                        .append("'" + path + "'").append(")");
                Cursor cur = cr.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                        new String[] { MediaStore.Images.ImageColumns._ID },
                        buff.toString(), null, null);
                int index = 0;
                for (cur.moveToFirst(); !cur.isAfterLast(); cur.moveToNext()) {
                    index = cur.getColumnIndex(MediaStore.Images.ImageColumns._ID);
                    // set _id value
                    index = cur.getInt(index);
                }
                if (index == 0) {
                    // do nothing
                } else {
                    Uri uri_temp = Uri
                            .parse("content://media/external/images/media/"
                                    + index);
                    if (uri_temp != null) {
                        uri = uri_temp;
                        Log.i("urishi", uri.toString());
                    }
                }
            }
        }
        return uri;
    }
    private String getPath(Uri uri) {
        String[] projection = {MediaStore.Video.Media.DATA};
        Cursor cursor = managedQuery(uri, projection, null, null, null);
        int column_index = cursor
                .getColumnIndexOrThrow(MediaStore.Video.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    }
    
}

